![](/img/trans.png)
[英]Rest-assured. Is it possible to extract JSONObject/JSONArray from response json?
[英]Rest-assured. How to check if not empty array is returned?
我有以下代码可以测试我的 RESTful API:
given().baseUri("http://...").get("/categories/all")
.then()
.body(
"results", not(empty())
);
API 返回以下响应:
{
"error": {
"type": "NotFoundException"
}
}
而且我希望测试因这种响应而失败。 但是测试通过了。
如何修改测试以使其失败? 只有当 API 返回一个在“results”键中包含非空数组的对象时,它才应该通过。 当“results”键不存在、包含空数组或包含不是数组的内容时,它应该会失败。
我想出了以下解决方案:
given().baseUri("http://...").get("/categories/all")
.then()
.body(
"results", hasSize(greaterThan(0))
);
如果“results”是空数组或不是数组,则失败。 如果“results”是一个非空数组,它就会通过。 它以可读的方式报告错误,例如:
Expected: a collection with size a value greater than <0>
Actual: null
我遇到了类似的问题,但在我的情况下,端点直接返回一个数组。 我对此的解决方案:
@Test
public void testNotEmpty() {
uAssured.given()
.when()
.get("resources/totest")
.then()
.statusCode(200)
.body("$.size()", greaterThan(0));
}
对于上面的示例,以下内容也应该有效:
@Test
public void testNotEmpty() {
uAssured.given()
.when()
.get("resources/totest")
.then()
.statusCode(200)
.body("results.size()", greaterThan(0));
}
要检查数组是否为空,您可以使用not(emptyArray)方法。
given()
.baseUri("http://...")
.get("/categories/all")
.then()
.body("results", not(emptyArray()));
使用 org.hamcrest.Matcher 中的 emptyArray 方法
我遇到了同样的问题,我发现以下指令有效:
given().baseUri("http://...").get("/categories/all")
.then()
.assertThat().body(notNullValue());
我尝试了以上所有方法,但没有运气。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.