Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

The API returns the following response:

{
    "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.

like image 949
JustAC0der Avatar asked Jan 20 '15 07:01

JustAC0der


2 Answers

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.:

Expected: a collection with size a value greater than <0>
Actual: null
like image 53
JustAC0der Avatar answered Sep 23 '22 15:09

JustAC0der


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));
}
like image 35
Stefan Großmann Avatar answered Sep 25 '22 15:09

Stefan Großmann