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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Improving Java Application Reliability with Dynatrace AI Engine
  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus
  • How Java Servlets Work: The Backbone of Java Web Apps

Trending

  • AI Paradigm Shift: Analytics Without SQL
  • Building a DevOps-Ready Internal Developer Platform: A Hands-On Guide to Golden Paths, Self-Service, and Automated Delivery Pipelines
  • Master-Class: Understanding Database Replication (Single, Multi, and Leaderless)
  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. How to Mock a Web Server in Your Java Applications

How to Mock a Web Server in Your Java Applications

To test an application that consumes a web API, you have two options: start a container or mock a web server. Today we'll discuss the latter using the WireMock simulator.

By 
Helber Belmiro user avatar
Helber Belmiro
DZone Core CORE ·
Oct. 04, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.9K Views

Join the DZone community and get the full member experience.

Join For Free

When you need to test an application that consumes a web API, you basically have two options:

  1. Use Testcontainers to start a container that will run the web API which your application will consume.
  2. Mock a Web Server to emulate the web API which your application will consume.

Many times, starting a container for that is not an option. For instance: you might not have a container environment available, or you just don’t have the artifacts to create that container (it might be a 3rd part API), or it is hard to emulate the needed behavior with containers.

Mocking a Web Server is an excellent alternative because it’s easy, flexible, and fast. And, using WireMock - an open-source simulator for HTTP-based APIs, makes the process easier and faster.

Mocking the Web Server With WireMock

The first thing you need to do is add WireMock as a dependency on your project.

XML
 
<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock-jre8</artifactId>
    <version>2.28.1</version>
    <scope>test</scope>
</dependency>


Next, in your test, create an attribute for your server. After that, create a method with the annotation @BeforeEach to set up your server before each test that you will run.

Java
 
private WireMockServer server; 

@BeforeEach
void 
    server = new WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort());
    server.start();
}


Note that we are using a dynamic port for the server. This means that the server will start using a random port, so we don’t have to worry if the port is already in use.

Next, you will create a method to shut down that server. This method will be called after each test that you will run. So, annotate it with @AfterEach.

Java
 
@AfterEach
void tearDown() {
    server.shutdownServer();
}


Next, create a method to mock the Web Server. You will call this method in your test later.

Java
 
private void mockWebServer() {
    server.stubFor(get("/my/resource")
          .willReturn(ok()
          .withBody("TheGreatAPI.com")));
}


In the above code, we’re telling WireMock to return the status OK with “TheGreatAPI.com” as the body when it receives a GET at “/my/resource”. Now, let’s create our test. We’ll create an HTTP request to the endpoint that we mocked above, and check if the result is what we expect.

Java
 
@Test
void test() throws Exception {
    mockWebServer();

    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
                                     .uri(URI.create("http://localhost:" + server.port() + "/my/resource"))
                                     .build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    assertEquals("TheGreatAPI.com", response.body());
}


Note that when we’re creating the HttpRequest, we have to inform the port where the endpoint is. Since we used a random port when we created the server, we don’t know which port the server used. So, we have to ask the server which port it’s using, by calling the method WireMockServer#port.

Your Test is Ready

To summarize, before each test you have to set up your server with the endpoints. In each test, you call the endpoints using the random port the server will provide you. And after each test, you’ll shut down the server.

Here’s the complete code that we created above:

Java
 
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static org.junit.jupiter.api.Assertions.assertEquals;

class HttpTest {

    private WireMockServer server;

    @BeforeEach
    void setUp() {
        server = new WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort());
        server.start();
    }

    @Test
    void test() throws Exception {
        mockWebServer();

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                                         .uri(URI.create("http://localhost:" + server.port() + "/my/resource"))
                                         .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        assertEquals("TheGreatAPI.com", response.body());
    }

    private void mockWebServer() {
        server.stubFor(get("/my/resource")
                .willReturn(ok()
                        .withBody("TheGreatAPI.com")));
    }

    @AfterEach
    void tearDown() {
        server.shutdownServer();
    }
}


If you have any questions or feedback, leave it in the comment section.

Web server Web API application Java (programming language)

Published at DZone with permission of Helber Belmiro. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Improving Java Application Reliability with Dynatrace AI Engine
  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus
  • How Java Servlets Work: The Backbone of Java Web Apps

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook