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:
- Java Development Kit (JDK)
- Eclipse IDE
- Rest Assured library
Setting Up the Project
- Open Eclipse IDE and create a new Java project.
- Right-click on the project and select Properties.
- In the Properties window, select Java Build Path and then click on the Libraries tab.
- Click on the Add External JARs button and add the Rest Assured library JAR file.
- Click on Apply and then OK.
- Writing the Test Cases
- Create a new Java class in the project and name it APITest.
- Import the required libraries:
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
- Right-click on the APITest class and select Run As > JUnit Test.
- 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.
Written by Purusothaman Ramanujam
← Back to blog