Skip to content
Home » How to Mock a Web Server Using WireMock in Your Java Applications

How to Mock a Web Server Using WireMock in Your Java Applications

web text

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.

You can use WireMock for that. WireMock is an open source simulator for HTTP-based APIs.

Mocking the Web Server With WireMock

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

<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.

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.

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

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

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.

@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:

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, leave a comment or send me a message on my social media.