Search code examples
rest-assuredhamcrest

Rest Assured - Response body verification


I have the below response and I need to validate the body.

Json :

[
   "Admin Login",
   "Admin Contact",
   "Administrator",
   "Ads-View"
]

Code :

@Test(groups = {"ITTest"})
public void testAdmin() 
{
    com.jayway.restassured.response.Response testAdminResponse = get("/Admin");
    testAdminResponse.then().assertThat().statusCode(200);
    testAdminResponse.then().assertThat().body("$",equalTo("["Admin Login", "Admin Contact", "Administrator", "Ads-View"]"));
}

I tried hamcrest matchers - equalTo, containsString, hasItems, hasItem but all in vain

How do I validate the body completely ?


Solution

  • If you are looking to validate the response as a whole and if you know for certain that the response will be of the below format

    [ "Admin Login", "Admin Contact", "Administrator", "Ads-View" ]

    Then you can, convert the response as a string and use Assert.assertEquals

    Assert.assertEquals(**response**, "[\n" + 
            "   \"Admin Login\",\n" + 
            "   \"Admin Contact\",\n" + 
            "   \"Administrator\",\n" + 
            "   \"Ads-View\"\n" + 
            "]");
    

    I ran it locally and it works fine for me

    RestAssured.baseURI = "http://127.0.0.1:3000/Admin";
    String **response** = RestAssured.given().
    when().get().then().extract().asString();
    Assert.assertEquals(response, "");
    System.out.println("Body is : " + response);