RestAssured #16 - API Automation Practice (Part 3)- Validate Crocodiles (GET Request)

What are Hamcrest Matchers?

Hamcrest Matchers is a library that provides a rich set of matchers for performing flexible and readable assertions in Java. It is commonly used in testing frameworks like JUnit and TestNG to write expressive and readable test assertions.

Hamcrest Matchers allows you to write assertions in a more fluent and natural language style, making it easier to understand the intent of the test and the expected outcome. The library provides a wide range of matchers that can be used to validate various types of objects and their properties.

Here are some examples of Hamcrest matchers:

  • equalTo: Checks if the actual value is equal to the expected value.

  • is: Checks if the actual value equals the expected value (alternative to equalTo).

  • containsString: Checks if a string contains a specific substring.

  • greaterThan, lessThan: Checks if a value is greater than or less than another value.

  • hasItem, hasItems: Checks if a collection contains specific items.

  • hasProperty: Checks if an object has a specific property with a given value.


Validate Crocodiles Details

End point (GET Request)- https://test-api.k6.io/my/crocodiles

Below are validations for crocodiles details -

  1. Status Code - 200

  2. Response Header

    1. Content-Type - application/json

    2. Content-Length is greater than 100

  3. Response Body

    1. Count of crocodile - 3

    2. Validate id is same when crocodiles was created

    3. Validate response body using condition

      1. Ids of crocodiles having age > 10

      2. Ids of crocodiles have sex is "F"


How to filter JSON using JSONPath expression

To filter json we need to use the JSONPath expression

methodName { it.fieldName operator condition-value }.output-field

Consider that we have below JSON

[
    {
        "id": 12361495,
        "name": "Test Crocodile1",
        "sex": "M",
        "date_of_birth": "2010-06-27",
        "age": 12
    },
    {
        "id": 12361496,
        "name": "Test Crocodile2",
        "sex": "F",
        "date_of_birth": "2018-06-27",
        "age": 4
    },
    {
        "id": 12361497,
        "name": "Test Crocodile3",
        "sex": "M",
        "date_of_birth": "2007-06-27",
        "age": 15
    }
]

To get crocodiles id having age greater than 10, we can use below expression to filter for above json

findAll { it.age > 10 }.id

Here "it" refers to the current element being evaluated within a JSONPath expression. It is a placeholder that allows you to perform operations or comparisons on the current element.

And to store ids into a list we can use the below code -

List<Integer> crocodileIdsListHavingAgeGreaterThan10 = jsonPath.getList("findAll { it.age > 10 }.id");

Apart from findAll other methods are

  • find - Returns the first element that matches the specified condition.

  • findAll - Returns all elements that match the specified condition.

  • findMap - Returns a map containing the key-value pairs of the first element that matches the condition.

  • findAllMap - Returns a list of maps, where each map contains the key-value pairs of an element that matches the condition.


Example

Test method to validate crocodiles - validateCrocodilesTest

First will create 3 crocodiles using POST request from 2D array

String[][] crocodileDetails = {{"Test Crocodile1","M","2010-06-27"},{"Test Crocodile2","F","2018-06-27"},{"Test Crocodile3","M","2007-06-27"}};

List<Integer> crocodileIds = new ArrayList<>();

for (String[] crocodileDetail : crocodileDetails) {
    createCrocodileResponse = createCrocodile(crocodileDetail[0], crocodileDetail[1], crocodileDetail[2]);
    assertThat(createCrocodileResponse.getStatusCode(), equalTo(201));
    crocodileIds.add(Integer.parseInt(createCrocodileResponse.getResponseBodyUsingKey("id")));
}

Validate status code and response header

APIResponseDetailsExtractor getCrocodileResponse = createCrocodileFlow.getCrocodile(authToken);

//Validate status code
assertThat(getCrocodileResponse.getStatusCode(),equalTo(200));

//Validate header
assertThat(getCrocodileResponse.getResponseHeaderUsingKey("Content-Type"),containsString("application/json"));

assertThat(Integer.parseInt(getCrocodileResponse.getResponseHeaderUsingKey("Content-Length")),greaterThan(100));

Validate response body

//Validate response body
JsonPath jsonPath = getCrocodileResponse.getResponseJsonPath();
int crocodilesCount = jsonPath.getList("").size();

assertThat(crocodilesCount,equalTo(crocodileDetails.length));
List<Integer> crocodileIdsList = jsonPath.getList("id");

assertThat(crocodileIdsList,hasItems(crocodileIds.get(0),crocodileIds.get(1),crocodileIds.get(2)));

//Validate response body using condition
List<Integer> crocodileIdsListHavingAgeGreaterThan10 = jsonPath.getList("findAll { it.age > 10 }.id");

assertThat(crocodileIdsListHavingAgeGreaterThan10,hasItems(crocodileIds.get(0),crocodileIds.get(2)));

List<Integer> crocodileIdsListHavingGenderFemale = jsonPath.getList("findAll { it.sex == 'F' }.id");

assertThat(crocodileIdsListHavingGenderFemale,hasItems(crocodileIds.get(1)));
@Test
public void validateCrocodilesTest() {

    APIResponseDetailsExtractor createCrocodileResponse;

    String[][] crocodileDetails = {{"Test Crocodile1","M","2010-06-27"},{"Test Crocodile2","F","2018-06-27"},{"Test Crocodile3","M","2007-06-27"}};
    List<Integer> crocodileIds = new ArrayList<>();
    for (String[] crocodileDetail : crocodileDetails) {
        createCrocodileResponse = createCrocodile(crocodileDetail[0], crocodileDetail[1], crocodileDetail[2]);
        assertThat(createCrocodileResponse.getStatusCode(), equalTo(201));
        crocodileIds.add(Integer.parseInt(createCrocodileResponse.getResponseBodyUsingKey("id")));
    }

    APIResponseDetailsExtractor getCrocodileResponse = createCrocodileFlow.getCrocodile(authToken);
    //Validate status code
    assertThat(getCrocodileResponse.getStatusCode(),equalTo(200));
    //Validate header
    assertThat(getCrocodileResponse.getResponseHeaderUsingKey("Content-Type"),containsString("application/json"));
    assertThat(Integer.parseInt(getCrocodileResponse.getResponseHeaderUsingKey("Content-Length")),greaterThan(100));
    //Validate response body
    JsonPath jsonPath = getCrocodileResponse.getResponseJsonPath();
    int crocodilesCount = jsonPath.getList("").size();
    assertThat(crocodilesCount,equalTo(crocodileDetails.length));
    List<Integer> crocodileIdsList = jsonPath.getList("id");
    assertThat(crocodileIdsList,hasItems(crocodileIds.get(0),crocodileIds.get(1),crocodileIds.get(2)));

    //Validate response body using condition
    List<Integer> crocodileIdsListHavingAgeGreaterThan10 = jsonPath.getList("findAll { it.age > 10 }.id");
    assertThat(crocodileIdsListHavingAgeGreaterThan10,hasItems(crocodileIds.get(0),crocodileIds.get(2)));

    List<Integer> crocodileIdsListHavingGenderFemale = jsonPath.getList("findAll { it.sex == 'F' }.id");
    assertThat(crocodileIdsListHavingGenderFemale,hasItems(crocodileIds.get(1)));
}

GET Request for crocodile details -

public APIResponseDetailsExtractor getCrocodile(String authToken) {
    Response response = RestAssured.given()
            .contentType(ContentType.JSON)
            .header("Authorization", "Bearer " + authToken)
            .get(crocodilesBasePath);

    response.then().log().all();

    return new APIResponseDetailsExtractor(response);
}

You can find full code at Git Hub Repo Link - https://github.com/sksingh329/RestAssuredTutorials

Did you find this article valuable?

Support SUBODH SINGH by becoming a sponsor. Any amount is appreciated!