Search code examples
javarest-assuredhamcrest

Test json result with hamcrest, order agnostic


I have an API that returns the following kind of body result, and I want to test it with Hamcrest on java17.

[
    {
        "name": "name1",
        "version": "x.x.x"
    },
    {
        "name": "name2",
        "version": "y.y.y"
    }
]

I woud like to test that I always get version = "x.x.x" for name1, and version = "y.y.y" for name2.

The following code works, but I would like a more order-agnostic test, as it takes into account the order of my elements:

given()...when()...then()
   .body("name[0]", is("foo"))
   .body("version[0]", is("0.0.0"))
   .body("name[1]", is("bar"))
   .body("version[1]", is("1.1.1"));
);

Solution

  • This would work:

    .body("find {it.name == 'name1'}.version", is("x.x.x"))
    .body("find {it.name == 'name2'}.version", is("y.y.y"));