Skip to content

Mockserver Module

Mock Server can be used to mock HTTP services by matching requests against user-defined expectations.

Usage example

The following example shows how to start Mockserver.

public static final DockerImageName MOCKSERVER_IMAGE = DockerImageName
    .parse("mockserver/mockserver")
    .withTag("mockserver-" + MockServerClient.class.getPackage().getImplementationVersion());

@Rule
public MockServerContainer mockServer = new MockServerContainer(MOCKSERVER_IMAGE);

And how to set a simple expectation using the Java MockServerClient.

try (
    MockServerClient mockServerClient = new MockServerClient(mockServer.getHost(), mockServer.getServerPort())
) {
    mockServerClient
        .when(request().withPath("/person").withQueryStringParameter("name", "peter"))
        .respond(response().withBody("Peter the person!"));

    // ...a GET request to '/person?name=peter' returns "Peter the person!"

    assertThat(SimpleHttpClient.responseFromMockserver(mockServer, "/person?name=peter"))
        .as("Expectation returns expected response body")
        .contains("Peter the person");
}

Adding this module to your project dependencies

Add the following dependency to your pom.xml/build.gradle file:

testImplementation "org.testcontainers:mockserver:1.19.0"
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>mockserver</artifactId>
    <version>1.19.0</version>
    <scope>test</scope>
</dependency>

Additionally, don't forget to add a client dependency org.mock-server:mockserver-client-java to be able to set expectations, it's not provided by the testcontainers module. Client version should match to the version in a container tag.