DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Java Microservices Testing — A Minimalist Approach

Java Microservices Testing — A Minimalist Approach

In this tutorial, we'll learn about using HttpClient for REST API microservices testing with Java.

Grzegorz Skorupa user avatar by
Grzegorz Skorupa
·
Jun. 05, 18 · Tutorial
Like (5)
Save
Tweet
Share
10.50K Views

Join the DZone community and get the full member experience.

Join For Free

To prepare integration tests of microservice's REST API you really don't need any additional tools other than the microservice itself and HttpUrlConnection class included in JDK.

In the matter of fact, you can even test such API without writing any code, using cURL. And this is the big advantage of the REST API, despite frequent criticism.

The article shows how to design test cases for microservice REST API using the minimum external dependencies. The REST API of the Cricket Microservices Framework (CMSF) will serve as an example.

Although it is possible and in the case of a quick functionality check - invaluable, using the simplest methods is not convenient when you need automation. For this reason, to create our tests we will use JUnit framework and the wrapper class for HttpUrlConnection.

Another useful trick to facilitate running a test session is to use an embedded microservice. It is worth considering whether this is possible because, thanks to this, we do not have to run a separate test environment.

HttpClient

HttpClient along with Request and StandardResult classes which are part of Cricket Microservices Framework provides several convenient methods to handle the HTTP request with Java. They were included in the CMSF for two main reasons: to avoid external dependencies and to ensure Android compatibility of the client classes.

The code below is the streamlined version of the original HttpClient (without SSL connection and self certificate handling).

package org.cricketmsf.out.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.cricketmsf.in.http.Result;
import org.cricketmsf.in.http.StandardResult;

public class HttpClient {

    private int timeout = 0;

    public Result send(Request request) {
        StandardResult result = new StandardResult();
        if (request == null) {
            result.setCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
            result.setMessage("Request is null");
        }
        String requestData = "";
        if (request.data != null) {
            if (requestData instanceof String) {
                requestData = (String) request.data;
            } else {
                requestData = request.data.toString();
            }
        }
        result.setCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
        try {
            URL urlObj = new URL(request.getUrl());
            HttpURLConnection con;
            con = (HttpURLConnection) urlObj.openConnection();
            con.setReadTimeout(timeout);
            con.setConnectTimeout(timeout);
            con.setRequestMethod(request.method);
            request.properties.keySet().forEach((key) -> {
                con.setRequestProperty(key, request.properties.get(key));
            });
            if (requestData.length() > 0 || "POST".equals(request.method) || "PUT".equals(request.method) || "DELETE".equals(request.method)) {
                con.setDoOutput(true);
                OutputStream os = con.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os);
                try {
                    out.write(requestData);
                    out.flush();
                    out.close();
                    os.close();
                } catch (IOException e) {
                    result.setCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
                    result.setMessage(e.getMessage());
                }
            }
            con.connect();
            result.setCode(con.getResponseCode());
            StringBuilder response;
            String inputLine;
            try {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                    response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                }
                result.setPayload(response.toString().getBytes());
            } catch (IOException e) {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()))) {
                    response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                }
                result.setMessage(response.toString());
            }
        } catch (IOException e) {
            result.setCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}


Test Cases

With the HTTP client in place, we can design required test cases for our REST API. As an example, let's test Cricket's user API.

It would be very convenient if we did not have to run the tested page in a separate thread and start the tests with one click. For services built using CMSF, this is possible thanks to the implemented hexagonal architecture. We can prepare the appropriate configuration of adapters and get a self-contained service. We can treat this configuration as a reference for further development of the website.

Let's create methods to run before and after calling tests, to start the service and generate a session token, and after performing all tests, call the proper shutdown.

/** 
* Run the microservice on localhost 
*/
@BeforeClass
public static void setup() {
    System.out.println("@setup");
    String[] args = {"-r", "-s", "Microsite"};
    service = Runner.getService(args);
    while (!service.isInitialized()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
    System.out.println("service is running");
    sessionToken = getSessionToken();
}

@AfterClass
public static void shutdown() {
    System.out.println("@shutdown");
    service.shutdown();
}

/**
* Log in to the service as user "demo" and get session token
*/
private static String getSessionToken() {
    // Given
    String login = "demo";
    String password = "cricket";
    String credentials = Base64.getEncoder()
           .encodeToString((login + ":" + password).getBytes());
    HttpClient client = new HttpClient();
    Request req = new Request()
            .setMethod("POST")
            .setProperty("Accept", "text/plain")
            .setProperty("Authentication", "Basic " + credentials)
            .setData("p=ignotethis") /*data must be added to POST or PUT requests */
            .setUrl("http://localhost:8080/api/auth");
    // When
    StandardResult response = (StandardResult) client.send(req);
    // Then
    Assert.assertEquals(200, response.getCode());
    String token = "";
    try {
        token = new String(response.getPayload(), "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        Assert.fail(ex.getMessage());
    }
    Assert.assertFalse(token == null || token.isEmpty());
    return token;
}

Then, test methods can use a running service to send requests and check responses.

@Test
public void readingPersonalDataOK() {
    // Given
    HttpClient client = new HttpClient();
    Request req = new Request()
            .setMethod("GET")
            .setProperty("Accept", "apNplication/json")
            .setProperty("Authentication", sessionToken)
            .setUrl("http://localhost:8080/api/user/")
            .setQuery("demo");
    // When
    StandardResult response = (StandardResult) client.send(req);
    // Then
    Assert.assertEquals(200, response.getCode());
    String data = null;
    try {
        data = new String(response.getPayload(), "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        Assert.fail(ex.getMessage());
    }
    Assert.assertFalse(data == null || data.isEmpty());
}

@Test
public void readingOtherUserPersonalDataNOK() {
    //Given
    HttpClient client = new HttpClient();
    Request req = new Request()
            .setMethod("GET")
            .setProperty("Accept", "application/json")
            .setProperty("Authentication", sessionToken)
            .setUrl("http://localhost:8080/api/user/")
            .setQuery("admin");
    // When
    StandardResult response = (StandardResult) client.send(req);
    // Then
    // The session token has been generated for user "demo", so accessing
    // "admin" account should not be possible.
    Assert.assertEquals(403, response.getCode());
}

And that's all. In a few simple steps, we have built a set of tests, working based on simple tools and at the same time, friendly for testing automation.

You can find the complete code in the Cricket Microservices Framework repository.

Conclusion

Testing REST API with Java is not as complicated as it is said. There are many tools that facilitate this task (several referenced above), so you can choose the one that suits you. However, it is always worth knowing what is going on underneath and not being completely dependent on the tool.

microservice Java (programming language) Testing API

Published at DZone with permission of Grzegorz Skorupa. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Boot, Quarkus, or Micronaut?
  • Front-End Troubleshooting Using OpenTelemetry
  • Create Spider Chart With ReactJS
  • 5 Software Developer Competencies: How To Recognize a Good Programmer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: