Categories: Uncategorised

REST API Automation Testing using Java

In this post we will see how to perform automation testing of REST API using Java. We will use the below sample API of get employees list.

To perform the automation we will use the Java’s HttpURLConnection. HTTPURLConnection from java.net package is a URLConnection along with support for HTTP-specific features. It can be used to send HTTP requests. Using HTTPURLConnection have implemented a method to send GET request and get the response. Similar implementation can be done to automate other HTTP methods.

public class Solution {

 private static HttpURLConnection connection = null;

 public static String sendGetRequest(String url) {
  URL getURL;
  StringBuffer response = new StringBuffer();
  try {
   getURL = new URL(url);
   connection = (HttpURLConnection) getURL.openConnection();
   connection.setRequestMethod("GET");
   int responseCode = connection.getResponseCode();
   if (responseCode == HttpURLConnection.HTTP_OK) {
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
     response.append(inputLine);
    }
    in.close();
   }

  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   connection.disconnect();
  }
  return response.toString();

 }
}

Then we will write a test to verify the expected and actual response are equal.

class SolutionTest {

 @Test
 void test() {
  
  assertEquals("[{\"employeeId\":1,\"name\":\"Bob\",\"department\":\"Food\"}]", Solution.sendGetRequest("http://localhost:8080/api/v1/employees"));
 }

}

mahendravarman.m@gmail.com

Recent Posts

Spring Webflux Functional Endpoint – File Upload

In this blog using the Spring WebFlux module, we are going to leverage the functional…

9 months ago

Serverless Functions with Spring Cloud Function, AWS Lambda

Spring Cloud Function is a project within the Spring ecosystem that allows developers to build…

9 months ago

Spring Boot + RabbitMQ – Decoupling Microservices Communication

RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP).…

9 months ago

Spring Integration – Sending files over SFTP

Spring Integration is a powerful extension of the Spring Framework designed to support the implementation…

9 months ago

Spring Cloud Config Client

The Spring Cloud Config Client is a component of the Spring Cloud framework that enables…

10 months ago

Handling CSV in Python

In Python, handling CSV (Comma Separated Values) files is easy using the built-in csv module.…

10 months ago