簡體   English   中英

使用 Lombok 反序列化 POJO 以發送大型 JSON 有效負載

[英]De-serialize a POJO using Lombok to send large JSON payload

我是一名 QA,正在使用 Rest Assured DSL 編寫一些測試。

這是我第一次嘗試使用 Lombok 反序列化 POJO 以用於 JSON 有效負載。

這種構建我的數據 object,Customer 的方式似乎很麻煩。 由於測試以 400 失敗,我假設我沒有正確序列化它,並且我不清楚如何將有效負載查看為 JSON。

我沒有使用顯式映射,因此假設 Rest Assured 默認使用 GSON。

鑒於我的 POJO:

import lombok.Data;

@Data
public class Customer {

    private String employeeCode;
    private String customer;
    private String firstName;
    private String lastName;
    private String title;
    private String dob;
    private String employeeId;

}

...以及我需要發送的示例有效負載:

{
    "employeeCode": "18ae56",
    "customer": {
        "firstName": "John",
        "lastName": "Smith",
        "title": "Mr",
        "dob": "1982-01-08", 
        "employeeId": "2898373"
    }
}

我的示例測試是:

 @BeforeClass
 public static void createRequestSpecification(){

    requestSpec = new RequestSpecBuilder()
            .setBaseUri("https://employee-applications.company.com")
            .setContentType(ContentType.JSON)
            .build();
}

   @Test
    public void createApplicationForNewCustomer(){

    Customer customer = Customer.builder().build();
    customer.setEmployeeCode("18ae56");
    customer.setFirstName("John");
    customer.setLastName("Smith");
    customer.setTitle("Mr");
    customer.setDob("1982-01-08");
    customer.setEmployeeId("2898373");

    given().
            spec(requestSpec).
    and().
            body(customer).
    when().
            post("/api/v6/applications").
    then().
            assertThat().statusCode(201);

}

您的 POJO 不正確,顯然序列化的 JSON 不是預期的格式

你應該有兩個班

下面是您的 POJO 應該如何生成給定的 JSON 結構

    @Data
    public static class Customer {

        @JsonProperty("firstName")
        private String firstName;
        @JsonProperty("lastName")
        private String lastName;
        @JsonProperty("title")
        private String title;
        @JsonProperty("dob")
        private String dob;
        @JsonProperty("employeeId")
        private String employeeId;

    }

    @Data
    public static class Example {

        @JsonProperty("employeeCode")
        public String employeeCode;
        @JsonProperty("customer")
        public Customer customer;

    }

和你的測試方法

Example e = new Example();
e.setEmployeeCode("18ae56");

Customer c = new Customer();
c.setFirstName("John");
c.setLastName("Smith");
c.setTitle("Mr");
c.setDob("1982-01-08");
c.setEmployeeId("2898373");

e.setCustomer(c);


given().spec(requestSpec).and().body(e).when().post("/api/v6/applications").then().assertThat()

最簡單的測試方法:

String abc = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(e);
System.out.println(abc);

或者

System.out.println(new Gson().toJson(e));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM