Search code examples
rest-assuredhamcrest

How to compare two JSON fields in RestAssured and Hamcrest?


I'm using RestAssured and Hamcrest to functional test our Back-end API and I'd like to know if there's any way to compare two distinct JSON fields inside the body method, or any equivalent.

For example, given the JSON response below:

[
  { name: "Foo", age: 25 },
  { name: "Bar", age: 30 }
]

And given the code below, with a little excerpt of an invalid source code line that exposes what I'm trying to achieve:

given()
  .when()
  .get("/my-endpoint")
  .then()
  .body("[0].age", lessThan("[1].age")); // Invalid code just to show what I need to do

How can I achieve the goal exposed above in a clean way?


Solution

  • I think I have found the best way of doing it. It's quite simple actually. I just need to:

    given()
      .when()
      .get("/my-endpoint")
      .then()
      .body("[0].age", resp -> lessThan(resp.path("[1].age"));