MockServer publishes official Testcontainers modules for six languages. Each module starts the official mockserver/mockserver Docker container, waits for it to be ready, and provides connection helpers (host, port, base URL). The container is started and stopped automatically by the test run — no manual server management is needed.

Language Package / registry Add dependency
Java org.mock-server:mockserver-testcontainers (Maven Central) <artifactId>mockserver-testcontainers</artifactId>
.NET MockServer.Testcontainers (NuGet) dotnet add package MockServer.Testcontainers
Node.js @mockserver/testcontainers (npm) npm install --save-dev @mockserver/testcontainers
Python testcontainers-mockserver (PyPI) pip install testcontainers-mockserver
Rust testcontainers-mockserver (crates.io) Add to [dev-dependencies] in Cargo.toml
Go github.com/mock-server/mockserver-monorepo/mockserver-testcontainers/go go get github.com/mock-server/mockserver-monorepo/mockserver-testcontainers/go
 

Java

MockServer publishes its own Testcontainers module, mockserver-testcontainers, that starts the official MockServer Docker image for the duration of a test and gives you a ready-wired client. It is the MockServer-maintained module and is kept in lockstep with each MockServer release.

Note: this module supersedes the older bundled org.testcontainers:mockserver module. The bundled module exposes only a single port, pins an old default image, and has no configuration helpers. New projects should use org.mock-server:mockserver-testcontainers described here.

Maven

<dependency>
    <groupId>org.mock-server</groupId>
    <artifactId>mockserver-testcontainers</artifactId>
    <version>7.2.0</version>
    <scope>test</scope>
</dependency>

Gradle

testImplementation 'org.mock-server:mockserver-testcontainers:7.2.0'

The module brings in Testcontainers and the MockServer Java client transitively, so no other MockServer dependency is required for a test.

Start the container, set up an expectation through the wired client, then point the system under test at the container endpoint. By default the image tag is derived from the MockServer client library on the classpath, so the container and client always match.

import org.mockserver.client.MockServerClient;
import org.mockserver.testcontainers.MockServerContainer;
import org.junit.jupiter.api.Test;

import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

class ExampleTest {

    @Test
    void shouldMockResponse() {
        try (MockServerContainer mockServer = new MockServerContainer()) {
            mockServer.start();

            MockServerClient client = mockServer.getClient();
            client
                .when(request().withPath("/hello"))
                .respond(response().withBody("world"));

            // point the system under test at mockServer.getEndpoint()
            // e.g. http://<host>:<mapped-port>/hello  ->  "world"
        }
    }
}

Use getEndpoint() / getSecureEndpoint() for the HTTP / HTTPS base URL (MockServer serves both on the same port), and getServerPort() for the mapped host port. The client returned by getClient() is cached and stopped automatically when the container stops.

Fluent helpers configure the container before it starts. Each returns the container for chaining.

HelperWhat it does
withServerPort(int)Change the port MockServer listens on inside the container.
withDnsPort(int)Enable the DNS resolver and expose the DNS port over UDP.
withTransparentProxy()Enable transparent proxy mode and add the NET_ADMIN capability. iptables / redirect rules remain your responsibility.
withHttp3(int)Enable experimental HTTP/3 (QUIC) and expose the port over UDP.
withInitializationJson(String)Copy an initialization JSON file into the container and load its expectations at startup.
withLogLevel(String)Set the MockServer log level (e.g. DEBUG).
withProperty(key, value) / withProperties(Map)Set any MockServer configuration property by its environment-variable name (e.g. MOCKSERVER_MAX_EXPECTATIONS).

To connect MockServer to other containers (for example an AsyncAPI broker), use the standard Testcontainers withNetwork(Network) and withNetworkAliases(String...) methods inherited from GenericContainer.

Pinning the image: to use a specific image instead of the version-matched default, pass a DockerImageName to the constructor:

new MockServerContainer(
    DockerImageName.parse("mockserver/mockserver:mockserver-7.2.0")
);
 

.NET

The MockServer.Testcontainers NuGet package integrates with the Testcontainers for .NET library. It starts a mockserver/mockserver container, waits for readiness, and exposes the mapped URL via helper methods. The C# namespace is Testcontainers.MockServer (NuGet's Testcontainers.* id prefix is reserved, so the install id and the using differ).

dotnet add package MockServer.Testcontainers

Requires .NET 8.0 SDK and Docker.

using Testcontainers.MockServer;

// Create and start a MockServer container
await using var container = new MockServerBuilder()
    .WithLogLevel("INFO")
    .Build();

await container.StartAsync();

// Get the connection URL
var url = container.GetUrl();        // http://localhost:xxxxx

// Use MockServer via its REST API
using var httpClient = new HttpClient();

// Create an expectation
var expectation = """
    {
        "httpRequest": { "method": "GET", "path": "/hello" },
        "httpResponse": { "statusCode": 200, "body": "world" }
    }
    """;

await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Put, $"{url}/mockserver/expectation")
{
    Content = new StringContent(expectation, System.Text.Encoding.UTF8, "application/json")
});

// Issue a request that matches the expectation
var response = await httpClient.GetStringAsync($"{url}/hello");
// response == "world"

Use GetUrl() for the HTTP base URL, GetSecureUrl() for HTTPS, and GetConnectionString() for host:port.

MethodWhat it does
WithLogLevel(string)Set the MockServer log level (INFO, DEBUG, WARN, ERROR, TRACE).
WithMockServerProperty(string, string)Set any MockServer configuration property as an environment variable.
WithImage(string)Override the Docker image.
WithPortBinding(int, int)Bind a specific host port to the container port.
 

Node.js

The @mockserver/testcontainers npm package integrates with the Testcontainers for Node.js library. It works with Node.js >= 18 and supports TypeScript out of the box.

npm install --save-dev @mockserver/testcontainers

Requires Docker to be running and Node.js >= 18.

import { MockServerContainer } from "@mockserver/testcontainers";

// Start a MockServer container (pulls the image if needed)
const container = await MockServerContainer.start();

// Get the URL to connect to
const url = container.getUrl(); // e.g. http://localhost:32789

// Create an expectation via the REST API
await fetch(`${url}/mockserver/expectation`, {
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    httpRequest: { method: "GET", path: "/hello" },
    httpResponse: { statusCode: 200, body: "world" },
  }),
});

// Make requests against the mock
const response = await fetch(`${url}/hello`);
console.log(await response.text()); // "world"

// Stop the container when done
await container.stop();

MockServerContainer.start(options?) accepts an optional image, serverPort, and env map. The started container exposes getUrl(), getEndpoint() (alias), getSecureEndpoint(), getHost(), and getPort().

 

Python

The testcontainers-mockserver PyPI package integrates with the Testcontainers for Python library (>= 4.0.0). It works with Python >= 3.9 and can be used as a context manager.

pip install testcontainers-mockserver

Requires Python >= 3.9, testcontainers >= 4.0.0, and Docker.

from testcontainers_mockserver import MockServerContainer
import requests

with MockServerContainer() as mockserver:
    url = mockserver.get_url()  # e.g. "http://localhost:49152"

    # Create an expectation
    requests.put(f"{url}/mockserver/expectation", json={
        "httpRequest": {"method": "GET", "path": "/hello"},
        "httpResponse": {"statusCode": 200, "body": "world"},
    })

    # Match it
    resp = requests.get(f"{url}/hello")
    assert resp.text == "world"

The container is automatically stopped when the with block exits. Helpers get_url(), get_secure_url(), get_host(), and get_port() expose the connection details.

MethodWhat it does
with_server_port(port)Override the listen port inside the container.
with_log_level(level)Set MOCKSERVER_LOG_LEVEL.
with_property(key, value)Set any MockServer environment variable.
with_initialization_json(path)Point to a startup expectations JSON file loaded at container start.
 

Rust

The testcontainers-mockserver crate integrates with the testcontainers crate. It supports both synchronous and async (Tokio) test runners.

Add to your Cargo.toml:

[dev-dependencies]
testcontainers-mockserver = "7.0"
testcontainers = { version = "0.23", features = ["blocking"] }
reqwest = { version = "0.13", features = ["blocking"] }

Requires Rust 1.70+ and Docker.

Synchronous

use testcontainers::runners::SyncRunner;
use testcontainers_mockserver::MockServer;

#[test]
fn test_with_mockserver() {
    let container = MockServer::default().start().unwrap();
    let base_url = testcontainers_mockserver::base_url(&container);

    // Create an expectation
    let client = reqwest::blocking::Client::new();
    client.put(format!("{base_url}/mockserver/expectation"))
        .header("Content-Type", "application/json")
        .body(r#"[{
            "httpRequest": { "method": "GET", "path": "/hello" },
            "httpResponse": { "statusCode": 200, "body": "world" }
        }]"#)
        .send()
        .unwrap();

    // Call the mocked endpoint
    let resp = client.get(format!("{base_url}/hello")).send().unwrap();
    assert_eq!(resp.status(), 200);
    assert_eq!(resp.text().unwrap(), "world");
}

Async (Tokio)

use testcontainers::runners::AsyncRunner;
use testcontainers_mockserver::MockServer;

#[tokio::test]
async fn test_with_mockserver_async() {
    let container = MockServer::default().start().await.unwrap();
    let base_url = testcontainers_mockserver::async_base_url(&container).await;
    // ... use base_url with an async HTTP client
}
use testcontainers_mockserver::MockServer;

let image = MockServer::new("mockserver-7.2.0")
    .with_env("MOCKSERVER_LOG_LEVEL", "DEBUG")
    .with_env("MOCKSERVER_MAX_EXPECTATIONS", "500")
    .with_server_port(9090);

with_env(key, value) sets any MockServer environment variable. with_server_port(port) overrides the container listen port.

 

Go

The Go module integrates with the Testcontainers for Go library. It starts and waits for the MockServer container, then provides URL(ctx) and ServerPort(ctx) helpers.

go get github.com/mock-server/mockserver-monorepo/mockserver-testcontainers/go

Requires Go 1.22+ and Docker.

package example_test

import (
    "context"
    "net/http"
    "strings"

    mockserver "github.com/mock-server/mockserver-monorepo/mockserver-testcontainers/go"
)

func Example() {
    ctx := context.Background()

    // Start a MockServer container
    ctr, err := mockserver.Run(ctx, mockserver.DefaultImage)
    if err != nil {
        // handle error
    }
    defer ctr.Terminate(ctx)

    // Get the base URL
    url, err := ctr.URL(ctx)
    if err != nil {
        // handle error
    }

    // Create an expectation
    expectation := `{
        "httpRequest": {"method": "GET", "path": "/hello"},
        "httpResponse": {"statusCode": 200, "body": "world"}
    }`
    req, _ := http.NewRequestWithContext(ctx, http.MethodPut, url+"/mockserver/expectation",
        strings.NewReader(expectation))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)

    // Call the mocked endpoint
    resp, _ := http.Get(url + "/hello")
    // resp.StatusCode == 200
}

mockserver.Run(ctx, image, opts...) accepts optional testcontainers.ContainerCustomizer values. The container waits for /mockserver/status to return HTTP 200 before Run returns. Use ctr.URL(ctx) for the HTTP base URL and ctr.ServerPort(ctx) for the mapped port.

For more information see Running MockServer via Testcontainers and the available MockServer clients.