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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Add Material-UI Table In ReactJS Application
  • 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

  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • A Guide to Developing Large Language Models Part 1: Pretraining
  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  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.7K 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

  • Add Material-UI Table In ReactJS Application
  • 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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!