jsonpathserenity-bddcucumber-serenity

Serenity-BDD jsonPath validation


I'm doing a serenity test and want to do some validation on json. The json I got looks like

{
    "devices": [
        {
            "deviceId": "0",
            "deviceName": "Device-0",
            "deviceStatus": "free",
            "claimer": "-",
            "claimedUntil": null
        },
        {
            "deviceId": "1",
            "deviceName": "Device-1",
            "deviceStatus": "free",
            "claimer": "-",
            "claimedUntil": null
        },
        ...
    ]
}

The order of the devices in this json is changing after I do some operations. I want to get a device by Id and want to validate the "claimer" and "deviceStatus".

My code look like:

@Then("see if device with id {string} is status {string}")
public void checkIfDeviceIsClaimed(String deviceId, String status) {
    theActorInTheSpotlight().should(seeThatResponse("Get valid",
        res -> res.statusCode(200)
            .body("$.devices.?(@.deviceId == " + deviceId + ").claimer", equalTo(theActorInTheSpotlight().getName()))
            .body("$.devices.?(@.deviceId == " + deviceId + ").deviceStatus", equalTo(status))));
  }

And my error looks like

Step failed
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: Unexpected input: 'restAssuredJsonRootObject.$.devices.[' @ line 1, column 37.
   restAssuredJsonRootObject.$.devices.[?(@.deviceId == 0)].claimer
                                       ^

Is there any possibility to change the JsonPath Lib or to achive the right behaviour?

Many thanks in advance


Solution

  • You can get result by using correct syntax.

    .body("devices.find {it.deviceId == '" + deviceId + "'}.claimer", equalTo(theActorInTheSpotlight().getName()))
    .body("devices.find {it.deviceId == '" + deviceId + "'}.deviceStatus", equalTo(status))));