How to Perform Multiple Assertions in Rest Assured?

When working with RESTful APIs in testing, it’s common to validate multiple aspects of the response, such as status codes, headers, and the response body. Rest Assured, a popular Java library for API testing, offers a powerful and flexible way to perform these validations.

In this blog post, we’ll explore how to perform multiple assertions in Rest Assured effectively.


Why Multiple Assertions?

While testing APIs, a single test case often involves validating several attributes of the API response:

  1. Status Code: Ensures the correct HTTP status is returned.
  2. Headers: Verifies that necessary headers (like Content-Type) are present and accurate.
  3. Response Body: Confirms that the response data matches expectations.

Having all assertions in one test case improves readability and reduces redundant test cases.


Approaches to Perform Multiple Assertions

1. Using the then() Method

Rest Assured allows multiple validations in a single chain using the then() method.

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;


public class MultiAssertionsExample {

    public static void main(String[] args) {

        given()

            .baseUri("https://jsonplaceholder.typicode.com")

            .basePath("/posts/1")

        .when()

            .get()

        .then()

            .statusCode(200) // Validate status code

            .header("Content-Type", "application/json; charset=utf-8") // Validate header

            .body("id", equalTo(1)) // Validate response body field

            .body("title", notNullValue()); // Ensure the title field is not null

    }

}

In this example:

  • We validate the status code is 200.
  • We check that the Content-Type header is correct.
  • We assert specific values in the response body.

2. Using Soft Assertions

Hard assertions (as seen above) stop the execution if a single validation fails. To continue execution even when an assertion fails, use Soft Assertions with libraries like AssertJ or TestNG.

Example with TestNG’s SoftAssert

import io.restassured.response.Response;
import org.testng.asserts.SoftAssert;

import static io.restassured.RestAssured.*;

public class SoftAssertionsExample {
    public static void main(String[] args) {
        Response response = given()
            .baseUri("https://jsonplaceholder.typicode.com")
            .basePath("/posts/1")
        .when()
            .get();

        // Initialize SoftAssert
        SoftAssert softAssert = new SoftAssert();

        // Perform multiple assertions
        softAssert.assertEquals(response.statusCode(), 200, "Status Code Mismatch");
        softAssert.assertEquals(response.header("Content-Type"), "application/json; charset=utf-8", "Header Mismatch");
        softAssert.assertEquals(response.jsonPath().getInt("id"), 1, "ID Mismatch");
        softAssert.assertNotNull(response.jsonPath().getString("title"), "Title is null");

        // Collate and report all assertions
        softAssert.assertAll();
    }
}

Here, softAssert.assertAll() collects and reports all failures at the end of the test.


3. Using Assertions with Hamcrest Matchers

Rest Assured integrates seamlessly with Hamcrest Matchers, making complex assertions easier.

Example:

import static io.restassured.RestAssured.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

import io.restassured.response.Response;

public class HamcrestExample {
    public static void main(String[] args) {
        Response response = given()
            .baseUri("https://jsonplaceholder.typicode.com")
            .basePath("/posts/1")
        .when()
            .get();

        // Perform assertions with Hamcrest
        assertThat(response.statusCode(), is(200));
        assertThat(response.header("Content-Type"), containsString("application/json"));
        assertThat(response.jsonPath().getString("title"), not(emptyOrNullString()));
    }
}

Hamcrest provides a rich set of matchers, making assertions more expressive and readable.


Best Practices

  1. Group Logical Assertions: Keep validations grouped logically (e.g., headers, body, status codes).
  2. Use Soft Assertions for Complex Tests: For tests requiring multiple independent checks, use soft assertions to ensure all verifications are executed.
  3. Log Failures Clearly: Use meaningful failure messages to quickly identify issues.

Followers