API Testing with Rest Assured in Java

API Testing Using Rest Assured

API testing is an essential part of software testing, and Rest Assured is a popular Java-based library used for testing RESTful 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:

  • Java Development Kit (JDK)
  • Eclipse IDE
  • Rest Assured library

Setting Up the Project

  1. Open Eclipse IDE and create a new Java project.
  2. Right-click on the project and select Properties.
  3. In the Properties window, select Java Build Path and then click on the Libraries tab.
  4. Click on the Add External JARs button and add the Rest Assured library JAR file.
  5. Click on Apply and then OK.

Writing the Test Cases

  1. Create a new Java class in the project and name it APITest.
  2. Import the required libraries:
import org.junit.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
  1. In the APITest class, create a test case method and annotate it with @Test.
@Test
public void testStatusCode() {    
  // test code goes here
}
  1. In the test case method, set the base URI of the API.
given().baseUri("https://jsonplaceholder.typicode.com");
  1. Add the API endpoint to the base URI.
given().baseUri("https://jsonplaceholder.typicode.com").get("/posts");
  1. 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

  1. Right-click on the APITest class and select Run As > JUnit Test.
  2. The test cases will execute, and you will see the results in the JUnit view.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *