Home > Software engineering >  Springboot RestAssured accessing elements of JSON array and validating fields not working
Springboot RestAssured accessing elements of JSON array and validating fields not working

Time:10-23

I am learning about RestAssured integration tests and have a Springboot REST API application that already uses JUnit 5 for unit tests. Now, I would like to add to it RestAssured integration tests so, I added RestAssured dependency to my REST API Springboot app I want to test like:

    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <scope>test</scope>
    </dependency>

Given I have response containing a JSON array with JSON object like this:

[
    {
        "id": 22,
        "type": "House",
        "size": 3000,
        "soldDate": "2021-03-10"
    },
    {
        "id": 27,
        "type": "Appartment",
        "size": "750",
        "soldDate": "2020-01-22"
    }
]

, I would like to use RestAssured to test this JSON response but I am running into issues. I am trying to test following:

    @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
            );

    }

However, every other attempt seem to not work except validating the hasSize(2) which executes without error.

CodePudding user response:

This would work for you:

.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"))
  • To get by index: remove dot., so $.[0].id --> [0].id

  • size is reversed keyword, so size --> getAt('size')

  • Related