Integration of Rest Assured with JUnit 5

  

Integrating RestAssured with JUnit 5 for API testing is a popular combination for writing clean, structured, and automated API tests in Java. Here's a detailed explanation and sample code:


What is RestAssured?

RestAssured is a Java-based library used to test RESTful APIs. It provides a domain-specific language (DSL) for making requests and validating responses.


What is JUnit 5?

JUnit 5 is the latest version of the popular unit testing framework for Java. It provides annotations, assertions, and other tools to write test cases.


Steps to Integrate RestAssured with JUnit 5

1. Add Maven Dependencies


<dependencies>
    <!-- RestAssured for API testing -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JUnit 5 -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.10.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JUnit 5 Engine -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.10.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>




Sample Test Code


package api;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

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

public class SampleApiTest {

    @BeforeAll
    public static void setup() {
        // Set the base URI for all tests
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
    }

    @Test
    public void testGetPosts() {
        given()
            .when()
            .get("/posts")
            .then()
            .statusCode(200)
            .body("size()", greaterThan(0));
    }

    @Test
    public void testGetPostById() {
        given()
            .when()
            .get("/posts/1")
            .then()
            .statusCode(200)
            .body("id", equalTo(1))
            .body("userId", notNullValue());
    }

    @Test
    public void testCreatePost() {
        String jsonBody = """
            {
                "title": "foo",
                "body": "bar",
                "userId": 1
            }
        """;

        given()
            .contentType(ContentType.JSON)
            .body(jsonBody)
            .when()
            .post("/posts")
            .then()
            .statusCode(201)
            .body("title", equalTo("foo"))
            .body("userId", equalTo(1));
    }
}




Explanation of Annotations

AnnotationDescription
@BeforeAllRuns once before all test methods in the class.
@TestMarks a method as a test case.


Assertions and Features Used

  • statusCode(200): Asserts the HTTP status.

  • body("id", equalTo(1)): Asserts the value in response body.

  • greaterThan(0): Asserts list size.

  • notNullValue(): Ensures the value is present.


How to Run

  • In Eclipse/IntelliJ:  Right-click the test class → Run as JUnit Test.
  • Using Maven:

mvn test

Integration of Rest Assured with JUnit 4

  

To integrate RestAssured with JUnit 4 for API testing, you can follow these steps:


Overview

  • RestAssured: A Java DSL for testing REST services.

  • JUnit 4: A popular unit testing framework for Java.

Integration Workflow

  • Add RestAssured and JUnit 4 dependencies.
  • Write test cases using JUnit 4 annotations (@Test@Before, etc.).
  • Use RestAssured to make HTTP requests and validate responses.


1. Maven Dependencies


<dependencies>
    <!-- RestAssured -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JUnit 4 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>

    <!-- JSON path (optional but useful) -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-path</artifactId>
        <version>5.4.0</version>
    </dependency>
</dependencies>




2. Simple GET API Test Example


import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.Before;
import org.junit.Test;

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

public class APITest {

    @Before
    public void setup() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
    }

    @Test
    public void testGetUser() {
        given().
            log().all().
        when().
            get("/users/1").
        then().
            log().all().
            assertThat().
            statusCode(200).
            body("id", equalTo(1)).
            body("username", notNullValue());
    }

    @Test
    public void testGetInvalidUser() {
        given().
            log().all().
        when().
            get("/users/9999").
        then().
            log().all().
            assertThat().
            statusCode(404);
    }
}




3. Explanation of Code


SectionDescription
@BeforeSets the base URI for all API requests.
given()Prepares the request (params, headers, etc.).
when()Specifies the request type (GET/POST/PUT/DELETE).
then()Asserts the response: status, body content, etc.
log().all()Logs request/response details to console (for debugging).


4. Run the Tests

You can run these tests using:

  • Eclipse/IntelliJ (right-click → Run as JUnit Test)

  • Maven CLI:


mvn test



5. Important Points:

  • Externalize base URLs using config files or environment variables.

  • Use @BeforeClass for expensive setups.

  • Use assertions to validate headers, response time, etc.

  • Use POJOs (Plain Old Java Objects) for complex JSON validation with RestAssured + Gson or Jackson.