Search code examples
jsonrestrest-assuredgpath

Rest assured, using Gpath query gives an error "The parameter "..." was used but not defined. Define parameters using the JsonPath.params(...)"


I'm new to rest-assured and I'm currently spiking it in order to implement it in our testing framework.

The problem I'm facing is to extract an object from a Json array from the REST response.

The example json I'm using:

{
    "MRData": {
        "xmlns": "http://ergast.com/mrd/1.4",
        "series": "f1",
        "url": "http://ergast.com/api/f1/2016/drivers.json",
        "limit": "30",
        "offset": "0",
        "total": "24",
        "DriverTable": {
            "season": "2016",
            "Drivers": [
                {
                    "driverId": "alonso",
                    "permanentNumber": "14",
                    "code": "ALO",
                    "url": "http://en.wikipedia.org/wiki/Fernando_Alonso",
                    "givenName": "Fernando",
                    "familyName": "Alonso",
                    "dateOfBirth": "1981-07-29",
                    "nationality": "Spanish"
                },
                {
                    "driverId": "bottas",
                    "permanentNumber": "77",
                    "code": "BOT",
                    "url": "http://en.wikipedia.org/wiki/Valtteri_Bottas",
                    "givenName": "Valtteri",
                    "familyName": "Bottas",
                    "dateOfBirth": "1989-08-28",
                    "nationality": "Finnish"
                }
            ]
        }
    }
}

Things i have tried so far:

This assertion is working

RestAssured.rootPath = "MRData.DriverTable.Drivers";
given()
.when()
.get("http://ergast.com/api/f1/2016/drivers.json")
.then()
.assertThat()
.body("find { find { d -> d.driverId == 'alonso' }.code }.code", equalTo("ALO"));

But I'm trying to actually get the Json of the particular array item

RestAssured.rootPath = "MRData.DriverTable.Drivers";
given()
.when()
.get("http://ergast.com/api/f1/2016/drivers.json")
.then()
.extract()
//.jsonPath().param("driverId", "alonso").get("find { d -> d.driverId == driverId }");
.path("find { d -> d.driverId == 'alonso' }");

Tried with both ways (one is commented out). But I get an error :

"The parameter "driverId" was used but not defined. Define parameters using the JsonPath.params(...)" 

Solution

  • RestAssured.rootPath = "MRData.DriverTable.Drivers"; works only for body expectations. For extraction you have to use full path to paramter e.g. MRData.DriverTable.Drivers.find { it.@driverId == 'alonso' }