Everything Java

← Back to blog

Published on 01/31/2024 12:05 by Purusothaman Ramanujam

API Testing with RestAssured

API testing is an essential part of software testing, and RestAssured is a popular Java-based library used for testing REST APIs. In this blog post, we will explore how to perform API testing using Rest Assured in Java.

Prerequisites

Before we start, make sure you have the following prerequisites installed:

Setting Up the Project

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

In the APITest class, create a test case method and annotate it with @Test.

@Test
public void testStatusCode() {    
  // test code goes here
}

In the test case method, set the base URI of the API.

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

Add the API endpoint to the base URI.

given().baseUri("https://jsonplaceholder.typicode.com").get("/posts");

Add assertions to the test case using the assertThat() method.

given()
.baseUri("https://jsonplaceholder.typicode.com")    
.get("/posts")    
.then()    
.assertThat()    
.statusCode(200)    
.body("size()", is(100));

In the above code, we are asserting that the API call should return a status code of 200 and the response body should contain 100 elements.

Running the Test Cases

Conclusion

In this blog post, we have learned how to perform API testing using Rest Assured in Java. Rest Assured provides a simple and easy-to-use API for testing RESTful APIs. With Rest Assured, you can write test cases that are easy to read and maintain.

Written by Purusothaman Ramanujam

← Back to blog