DevQAExpert

Assertions In Rest Assured 

Assertions are essential for confirming expected behavior and guaranteeing the accuracy of API answers in the context of API testing. Numerous assertion options are available in Rest Assured, a popular Java testing framework, to validate various API response characteristics. This blog post explores the various sorts of assertions offered by the Rest Assured framework and offers usage examples.

For API testing to be successful and ensure that APIs function as intended, effective assertion techniques are essential. By providing a wide range of assertion choices that include everything from headers, response times, cookies, and custom criteria to status codes and response contents, Rest Assured streamlines this process.

In order to enable testers to validate various aspects of API responses, this blog article tries to clarify the many sorts of assertions that Rest Assured provides. Testers can improve the accuracy and dependability of their API tests by comprehending and using these assertion capabilities.

We will discuss important assertion types like status code assertions, response header and body assertions, response time assertions, cookie and session assertions, schema validation assertions, and custom assertions throughout this blog post. Every assertion type has a specific function and adds to a thorough API testing strategy.

Testing professionals may create strong API tests that completely validate API answers by understanding the subtleties of these assertion types and knowing how to use them in Rest Assured tests. The examples presented in this blog post will explain how to assert status codes, response body fields, response headers, response times, cookies, and sessions, as well as how to carry out schema validation and create custom assertions. They will also demonstrate how to assert response timings, cookies, and sessions.

Testers can build comprehensive API tests that validate different facets of the API answers using Rest Assured’s flexible assertion capabilities. Testers can guarantee the precision, dependability, and conformance of their APIs by using a variety of assertion techniques, which will inevitably result in software applications of a higher caliber.

 

  • Status Code Assertion:

The most basic kind of assertion used in API testing is the status code assertion. It enables you to confirm the HTTP status code that the API endpoint returned. Using the statusCode() method, Rest Assured offers a concise and easy-to-understand syntax for asserting the anticipated status code. For instance:

 

given()
.get(“/users/1”)
.then()
.statusCode(200);

 

  • Response Body Assertion:

Rest Assured offers various options to assert the response body, which is often the most critical aspect of API testing. You can use methods like body(), jsonPath(), or xmlPath() to extract specific values from the response body and perform assertions on them. For example, to assert that the response body contains a specific field with a certain value:

given()

.get(“/users/1”)
.then()
.body(“name”, equalTo(“John Doe”));

  • Response Headers Assertion:

Headers in API responses can contain crucial data. You can assert certain headers, many headers, or the presence of a specified value within a header by using Rest Assured’s methods such as header(), headers(), or headerContains(). As an illustration, to confirm the existence of a “Content-Type” header

 

given()
    .get(“/users/1”)
.then()
  .header(“Content-Type”, containsString(“application/json”));

 

  • Response Time Assertion:

Verifying response times is a component of API performance testing. You can use methods like time() or timeIn() to assert response times with Rest Assured. To claim that the reaction time falls inside a certain range, for instance:

 

given()
    .get(“/users/1”)
.then()
    .time(lessThan(1000));

 This assertion checks if the response time is less than 1000 milliseconds.

  • Cookie and Session Assertion:

Methods are available through Rest Assured to assert cookies and sessions in API responses. Specific cookies or sessions can be validated using the cookie(), cookies(), or sessionValidation() methods. To confirm the existence of a certain cookie, for instance:

 

given()
    .get(“/users/1”)
.then()
    .cookie(“session_id”);

 This assertion verifies that the “session_id” cookie is present in the response.

  • Schema Validation Assertion:

Schema validation is essential to ensuring the integrity and structure of API responses. With the help of Rest Assured’s integration with well-known JSON and XML schema validators, you can check API replies against established schemas. To claim, for instance, that the response adheres to a JSON schema:

 

given()
    .get(“/users/1”)
.then()
    .assertThat()
    .body(matchesJsonSchemaInClasspath(“user_schema.json”));

 This assertion validates that the response matches the specified JSON schema.

  • Custom Assertion:

Rest Assured enables you to develop custom assertions suited to your particular testing requirements in addition to the built-in assertion techniques. You can create your own assertions to verify complex or domain-specific requirements by utilizing Java’s flexibility and the Rest Assured framework. Making a custom assertion, for instance, to determine whether a particular field is included in the response

 

given()
    .get(“/users/1”)
.then()
    .assertThat()
.body(response-> assertNotNull(response.path(“name”)));

 This custom assertion ensures that the “name” field exists in the response body.

  • Array Assertion:

You can assert elements from an array in the response body while using Rest Assured. For instance, to make that a certain value is present in an array:

 

given()
    .get(“/users”)
.then()
    .body(“name”, hasItem(“John Doe”));

This assertion checks if the “name” field in any element of the array contains the value “John Doe”.

 

  • Collection Size Assertion:

Using Rest Assured, you may state in the response body how big a collection is. To make sure that the response body has, for instance, a certain number of elements:

 

given()
    .get(“/users”)
.then()
    .body(“size()”, equalTo(5));

 

This assertion checks if the size of the collection in the response body is equal to 5.

 

  • Response Body Path Assertion:

With Rest Assured, you can use a path expression in the response body to assert particular values. For instance, to confirm that a nested field contains a particular value:

 

given()
    .get(“/users/1”)
.then()
    .body(“address.city”, equalTo(“New York”));

 

This assertion determines whether “New York” is the value of the “city” field in the “address” object.

 

  • Response Body List Assertion:

You can assert certain values within a list of objects that make up the response body. For example, to guarantee that every entry in the list possesses a particular property:

 

given()
    .get(“/users”)
.then()
    .body(“findAll { it.age > 18 }.size()”, equalTo(3));

 

This claim determines if the “age” attribute of precisely three elements in the list is larger than 18.

 

  • Response Body Mapping Assertion:

You can translate the response body to a Java object using Rest Assured and make assertions about its properties. Assuming, for instance, that a User class has attributes like “name” and “email”:

 

User user = given()
                .get(“/users/1”)
            .then()
                .extract()
                .as(User.class);

 

assertEquals(“John Doe”, user.getName());

assertEquals(“johndoe@example.com”, user.getEmail());

 

These claims verify that the “name” and “email” fields of the mapped User object have the anticipated values.

 

  • Response Body XPath Assertion:

XPath assertions are supported by Rest Assured if the API answer is in XML format. To assert, for instance, the value of an XML element:

 

given()
    .get(“/users/1”)
.then()
    .body(hasXPath(“//user/name[text()=’John Doe’]”));

 

This assertion determines whether the “user” node of the XML response contains the element “name” with the value “John Doe”.

 

  • Response Body Array Size Assertion:

You can assert the array’s size in the response body using Rest Assured. For instance, to guarantee that an array contains a certain amount of elements:

 

given()
    .get(“/users”)
.then()
    .body(“size()”, equalTo(10));

 

This claim verifies that the array’s size in the response body is equal to 10.

  • Response Body Null Assertion:

There is a choice in Rest Assured to assert if a certain field in the response body is empty. To confirm, for instance, if a field is null:

 

given()
    .get(“/users/1”)
.then()
    .body(“address”, is(nullValue()));

 

This assertion determines whether the response body’s “address” field is empty.

 

Conclusion 

We investigated the many assertion types that the Rest Assured framework for API testing offers. In order to confirm expected behavior and guarantee the accuracy of API answers, assertions are essential. You can validate different facets of the API answers using the extensive range of assertion options that Rest Assured offers.

We discussed a variety of assertion types, including claims about status codes, response bodies, response headers, response times, cookies and sessions, schema validation, and custom assertions. Every assertion type has a distinct function and aids in ensuring the precision, dependability, and conformity of API answers.

You can validate response times, ensure the accuracy of cookies and sessions, ensure the presence and values of specific fields in the response body, assert the presence and values of headers, validate response schemas, and create custom assertions to satisfy particular testing requirements by using Rest Assured’s assertion capabilities.

The examples given throughout the blog article demonstrated how to implement assertions in Rest Assured tests and showed the practical use of each assertion type. These examples illustrated how to perform schema validation, develop custom assertions, and assert status codes, response body fields, response headers, response timings, cookies, and sessions.

You may create strong API tests that validate multiple parts of API answers by utilizing the assertion features of Rest Assured, thereby ensuring the dependability and quality of your API endpoints. You can quickly create and carry out thorough API tests that cover a variety of scenarios using Rest Assured’s flexible and user-friendly assertion syntax.

Finally, knowing and successfully utilizing the various assertion types offered by Rest Assured enables you to develop exhaustive and trustworthy API tests, resulting in more resilient and high-quality software systems.