Tuesday 7 May 2019

Interview | RestAssured | Gpath | Groovy GPath in REST Assured,

Easy way to query Json Response object using - inbuilt feature of Rest Assured - Gpath

API :http://www.test.com/teams/88
Resp:
{
  "id": 88,
  "name": "Selenium"
}


@Test
public void gpath_extractSingleValue_findSingleTeamName() {
Response response = RestAssured.get("teams/88");
    String teamName = response.path("name");
    System.out.println(teamName);
}

A quick note on the .path() method. How did REST Assured know to use JSONPath, instead of XMLPath? We didn’t specify it! That’s some of the magic of GPath in REST Assured


@Test
public void gpath_extractSingleValue_findSingleTeamName_responseAsString() {
    String responseAsString = get("teams/88").asString();
    String teamName = JsonPath.from(responseAsString).get("name");
    System.out.println(teamName);
}

@Test
public void gpath_extractSingleValue_findSingleTeamName_getEverythingInOneGo() {
    String teamName = get("teams/88").path("name");
    System.out.println(teamName);
}

Other Samples:
Fist Child - response.path("teams.name[0]");
Last Child - response.path("teams.name[-1]");
All Childs -  ArrayList<String> allTeamNames = response.path("teams.name");
All Parents Data - ArrayList<Map<String,?>> allTeamData = response.path("teams");
Query - object.teams.find { it.name == 'Leicester City FC' }

RestAssuredAssertion :

@Test
public void gpath_extractSingleValue_findSingleTeamName_useAssertion() {
    given().
    when().
            get("teams/66").
    then().
            assertThat().
            body("name", equalTo("Manchester United FC"));
}

No comments:

Post a Comment