在REST Assured中,如何检查响应中是否存在字段?

问题描述 投票:16回答:4

我怎样才能确保我的响应(包括它是JSON)包含或不包含特定字段?

when()
    .get("/person/12345")
.then()
    .body("surname", isPresent()) // Doesn't work...
    .body("age", isNotPresent()); // ...But that's the idea.

我正在寻找一种方法来断言我的JSON是否包含字段age和surname。

java rest rest-assured
4个回答
37
投票

您也可以在JSON字符串上使用Hamcrest匹配器hasKey()(来自org.hamcrest.Matchers类)。

when()
    .get("/person/12345")
.then()
    .body("$", hasKey("surname"))
    .body("$", not(hasKey("age")));

0
投票

您可以像这样使用equals(null):

.body("surname", equals(null))

如果该字段不存在,则它将为null


0
投票

检查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();

0
投票

使用:import static org.junit.Assert.assertThat;

那你可以:assertThat(response.then().body(containsString("thingThatShouldntBeHere")), is(false));

© www.soinside.com 2019 - 2024. All rights reserved.