java 放心。如何检查是否返回非空数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28039981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:54:28  来源:igfitidea点击:

Rest-assured. How to check if not empty array is returned?

javajsonrestrest-assured

提问by JustAC0der

I have the following code which should test my RESTful API:

我有以下代码可以测试我的 RESTful API:

given().baseUri("http://...").get("/categories/all")
    .then()
    .body(
        "results",  not(empty())
    );

The API returns the following response:

API 返回以下响应:

{
    "error": {
        "type": "NotFoundException"
    }
}

And I want the test to fail for such response. But the test passes.

而且我希望测试因这种响应而失败。但是测试通过了。

How can I modify the test to make it fail? It should only pass if the API returns an object which contains a not-empty array in the "results" key. It should fail when the "results" key does not exists, contains empty array or when it contains something that is not an array.

如何修改测试以使其失败?只有当 API 返回一个在“results”键中包含非空数组的对象时,它才应该通过。当“results”键不存在、包含空数组或包含不是数组的内容时,它应该会失败。

回答by JustAC0der

I came up with the following solution:

我想出了以下解决方案:

given().baseUri("http://...").get("/categories/all")
    .then()
    .body(
        "results", hasSize(greaterThan(0))
    );

It fails if "results" is an empty array or not an array. It passes if "results" is a not-empty array. It reports an error in a readable way, e.g.:

如果“results”是空数组或不是数组,则失败。如果“results”是一个非空数组,它就会通过。它以可读的方式报告错误,例如:

Expected: a collection with size a value greater than <0>
Actual: null

回答by Stefan Gro?mann

I hat a similar problem but in my case the endpoint direcly returns an array. My solution for this:

我遇到了类似的问题,但在我的情况下,端点直接返回一个数组。我对此的解决方案:

@Test
public void testNotEmpty() {
    uAssured.given()
            .when()
                .get("resources/totest")
            .then()
                .statusCode(200)
                .body("$.size()", greaterThan(0));
}

For the example above the following should work as well:

对于上面的示例,以下内容也应该适用:

@Test
public void testNotEmpty() {
    uAssured.given()
            .when()
                .get("resources/totest")
            .then()
                .statusCode(200)
                .body("results.size()", greaterThan(0));
}

回答by Anoop Pednekar

To check if array is not empty you can use not(emptyArray)method.

要检查数组是否为空,您可以使用not(emptyArray)方法。

   given()
  .baseUri("http://...")
  .get("/categories/all")
  .then()
  .body("data", not(emptyArray()));

use emptyArray method from org.hamcrest.Matcher

使用 org.hamcrest.Matcher 中的 emptyArray 方法