Search code examples
testingrest-assuredrest-assured-jsonpath

Problems matching a long value in Rest Assured json body


I have the following response:

[
    {
        "id": 53,
        "fileUri": "abc",
        "filename": "abc.jpg",
        "fileSizeBytes": 578466,
        "createdDate": "2018-10-15",
        "updatedDate": "2018-10-15"
    },
    {
        "id": 54,
        "fileUri": "xyz",
        "filename": "xyz.pdf",
        "fileSizeBytes": 88170994,
        "createdDate": "2018-10-15",
        "updatedDate": "2018-10-15"
    }
]

and I am trying to match the id value to the object in JUnit like so:

RestAssured.given() //
                .expect() //
                .statusCode(HttpStatus.SC_OK) //
                .when() //
                .get(String.format("%s/%s/file", URL_BASE, id)) //
                .then() //
                .log().all() //
                .body("", hasSize(2)) //
                .body("id", hasItems(file1.getId(), file2.getId()));

But when the match occurs it tries to match an int to a long. Instead I get this output:

java.lang.AssertionError: 1 expectation failed.
JSON path id doesn't match.
Expected: (a collection containing <53L> and a collection containing <54L>)
  Actual: [53, 54]

How does one tell Rest Assured that the value is indeed a long even though it might be short enough to fit in an int? I can cast the file's id to an int and it works, but that seems sloppy.


Solution

  • The problem is that when converting from json to java type, int type selected, one solution is to compare int values. instead of

    .body("id", hasItems(file1.getId(), file2.getId()));
    

    use

    .body("id", hasItems(new Long(file1.getId()).intValue(), new Long(file2.getId()).intValue()));