Testing REST APIs is crucial to modern software development, ensuring the backend services work as expected. This guide provides a step-by-step process to set up API automation using Java with RestAssured and TestNG in Visual Studio Code (VS Code). By the end of this guide, you will be able to run automated API tests efficiently, ensuring the reliability and functionality of your APIs.
Here’s a concise guide to setting up API automation using Java with RestAssured and TestNG in VS Code:
Before beginning, ensure you have Java, Maven, and Visual Studio Code installed on your machine. These tools are essential for developing and running your API tests.
To add the necessary dependencies for RestAssured and TestNG, edit the pom.xml file of your Maven project and include the following:
<dependencies> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.4.0</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.4.0</version> <scope>test</scope> </dependency> </dependencies>
Create a new Java class ‘ApiService.java’ in ‘src/main/java/com/example/api’ and implement the API methods for GET, POST, and PUT requests.
import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; public class ApiService { public Response getRequest(String url) { return RestAssured.get(url); } public Response postRequest(String url, String jsonPayload) { return RestAssured.given() .contentType(ContentType.JSON) .body(jsonPayload) .post(url); } public Response putRequest(String url, String jsonPayload) { return RestAssured.given() .contentType(ContentType.JSON) .body(jsonPayload) .put(url); } }
import io.restassured.response.Response; import org.testng.Assert; import org.testng.annotations.Test; public class ApiServiceTest { ApiService apiService = new ApiService(); @Test public void testGetRequest() { Response response = apiService.getRequest("paste your url"); Assert.assertEquals(response.getStatusCode(), 200); System.out.println("GET Response: " + response.getBody().asString()); } }
You can run your TestNG tests by right-clicking on the test file and selecting Run As > TestNG Test or using Maven:
Right-click TestNg and run testng OR mvn test
Following these steps, you can set up a robust API testing framework in VS Code using Java, RestAssured, and TestNG. This setup ensures that your API endpoints are tested for various scenarios, enhancing the reliability and performance of your backend services.