Search code examples
hamcrestrest-assured

Dealing arrays with hamcrest and rest assured


I can't figure out how to create the code using hamcrest to check an array inside array having these properties.

(Imagine this as it has multiple entries with different data)

 {
        "mobilenum": "+6519829340",
        "firstname": "Allen",
        "lastname": "Edwards",
        "location": "Singapore"
    }

If I use this:

 .body("smsentries.mobilenum", contains(equalTo("+6519829340")));

it returns that it does exist but how can I put more checks that the object it has found also has the same firstname, lastname and location?

I also think that this is wrong:

 .body("smsentries.mobilenum", contains(equalTo("+6519829340")))
      .and()
 .body("smsentries.firstname", contains(equalTo("Allen"));

As what I understand here is that it searches the array if the array contains mobilenum equal to what is provided and if the array contains the name "Allen"

What I needed to is to find the array having the mobilenum equal to "+6519829340" and having the firstname equalto "Allen".

Do you guys and gals have any idea how to go about this?


Solution

  • What I needed to is to find the array having the mobilenum equal to "+6519829340" and having the firstname equalto "Allen".

    You can make use of the "find" method:

    .body("smsentries.find { it.mobilenum == '+6519829340' }.firstname", equalTo("Allen")
    .body("smsentries.find { it.mobilenum == '+6519829340' }.lastname", equalTo("Edwards").
    

    As you see you're essentially duplicating the path expression in the two cases so to improve this we can make use of root paths:

    .root("smsentries.find { it.mobilenum == '+6519829340' }").    
    .body("firstname", equalTo("Allen")
    .body("lastname", equalTo("Edwards").
    

    You can also parameterize root paths:

    .root("smsentries.find { it.mobilenum == '%s' }").    
    .body("firstname", withArgs("+6519829340"), equalTo("Allen")
    .body("lastname", withArgs("+6519829340"), equalTo("Edwards").
    .body("firstname", withArgs("+12345678"), equalTo("John")
    .body("lastname", withArgs("+12345678"), equalTo("Doe").