我怎样才能确保我的响应(包括它是JSON)包含或不包含特定字段?
when()
.get("/person/12345")
.then()
.body("surname", isPresent()) // Doesn't work...
.body("age", isNotPresent()); // ...But that's the idea.
我正在寻找一种方法来断言我的JSON是否包含字段age和surname。
您也可以在JSON字符串上使用Hamcrest匹配器hasKey()(来自org.hamcrest.Matchers
类)。
when()
.get("/person/12345")
.then()
.body("$", hasKey("surname"))
.body("$", not(hasKey("age")));
您可以像这样使用equals(null):
.body("surname", equals(null))
如果该字段不存在,则它将为null
检查wheedver字段是否为空。例如:
Response resp = given().contentType("application/json").body(requestDto).when().post("/url");
ResponseDto response = resp.then().statusCode(200).as(ResponseDto.class);
Assertions.assertThat(response.getField()).isNotNull();
使用:import static org.junit.Assert.assertThat;
那你可以:assertThat(response.then().body(containsString("thingThatShouldntBeHere")), is(false));