我正在学习RestAssured集成测试,并且有一个Springboot REST API应用程序已经使用JUnit 5进行单元测试。现在,我想添加RestAssured集成测试,所以,我添加RestAssured依赖到我的REST API Springboot应用程序,我想测试如下:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
如果我有响应包含JSON数组JSON对象像这样:
[
{
"id": 22,
"type": "House",
"size": 3000,
"soldDate": "2021-03-10"
},
{
"id": 27,
"type": "Appartment",
"size": "750",
"soldDate": "2020-01-22"
}
]
,我想使用RestAssured来测试这个JSON响应,但我遇到了问题。我想测试以下内容:
@Test
final void restAssuredTestGetAllCars() {
get("myapp/cars")
.then().statusCode(200) //validate status code
.and()
.body("$", hasSize(2)) // GOOD: validate size of the json array (root)
.body("$.[0].id", hasItem(22)) //FAIL: validate 1st JSON object id
.body("$.[0].type", hasItem("House")) //FAIL: validate 1st JSON object type
.body("$.[0].size", hasItem(3000)) //FAIL: validate 1st JSON object size
.body("$.[0].soldDate", hasItem("2021-03-10")) //FAIL: validate 1st JSON object size
... also validate 2nd JSON object same way as above by accessing [1] index
... then validate using hasItems like below
.body("id", hasItems(22, 27)) //FAIL: validate all ids are present in response
.body("type", hasItems("House", "Appartment")) //FAIL: validate all types are present in response
.body("size", hasItems("3000", "750")) //FAIL: validate all sizes are present in response
.body("soldDate", hasItems("2020-03-10", "2020-01-22")) //FAIL: validate all sizes are present in response
);
}
然而,除了验证hasSize(2)
执行无误外,其他所有尝试似乎都不起作用。
这将为您工作:
.body("$", hasSize(2))
.body("[0].id", equalTo(22))
.body("[0].type", equalTo("House"))
.body("[0].size", equalTo(3000))
.body("[0].soldDate", equalTo("2021-03-10"))
.body("id", hasItems(22, 27))
.body("type", hasItems("House", "Appartment"))
.body("getAt('size')", hasItems(3000, 750)) //In response: 3000, "750"
.body("soldDate", hasItems("2021-03-10", "2020-01-22"))
按索引获取:删除点
.
,即$.[0].id
—>[0].id
size
是反向关键字,所以size
——>getAt('size')