目录
代码依赖
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
</dependencies>
POJO类代码
public class Order {
public int id;
public int petId;
public int quantity;
public String shipDate;
public String status;
public boolean complete;
public int getId(){
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPetId() {
return petId;
}
public void setPetid(int petId){
this.petId = petId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getShipDate(){
return shipDate;
}
public void setShipDate(String shipDate) {
this.shipDate = shipDate;
}
public boolean getComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public Order(){}
public Order(int id, int petId, int quantity, String shipDate, String status, boolean complete) {
this.id = id;
this.petId = petId;
this.quantity = quantity;
this.shipDate = shipDate;
this.status =status;
this.complete = complete;
}
}
POJO对象转换成Json对象(序列化)
@Test
public void testSerializationUsingPOJO() throws JsonProcessingException {
// 初始化POJO对象
Order order = new Order(11, 198772, 8, "2022-08-10T12:04:09.926+00:00", "approved", true);
// 将POJO对象转化成json格式数据
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(order);
System.out.println(jsonStr);
given().
contentType("application/json").
body(jsonStr).
when().
post("https://petstore3.swagger.io/api/v3/store/order").
then().
statusCode(200);
}
Json对象转换成POJO对象(反序列化)
@Test
public void testDeSerialization() throws JsonProcessingException {
// 获取response返回的json数据
String responseBody = given().
header("Content-Type", "application/json").
get("https://petstore3.swagger.io/api/v3/store/order/11").
getBody()
.asString();
System.out.println(responseBody);
//将json数据转化成POJO对象
ObjectMapper objectMapper1 = new ObjectMapper();
Order orderData = objectMapper1.readValue(responseBody, Order.class);
Assert.assertEquals(orderData.getStatus(), "approved");
}