Testcontainers
MockServer publishes official Testcontainers modules for eight languages. Each module starts the official mockserver/mockserver Docker container, waits for it to be ready, and provides connection helpers (host, port, base URL) plus — for every language except Go — a ready-wired MockServer client. The container is started and stopped automatically by the test run — no manual server management is needed.
Version-matched image: every module derives its default image tag from the MockServer client version, so the container image stays in lockstep with the client library (falling back to the mutable latest tag when the version cannot be resolved). Pass an explicit image to any module to pin a specific version.
Keeping tests fast: for the patterns that keep container-based test suites quick — one container per suite with reset() between tests, container reuse, memory limits, and in-process alternatives for JVM tests — see Fast Tests: Startup Time, Memory and Reuse.
| 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 |
| Ruby | testcontainers-mockserver (RubyGems) | gem install testcontainers-mockserver |
| PHP | mock-server/mockserver-testcontainers (Packagist) | composer require --dev mock-server/mockserver-testcontainers |
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.4.0</version>
<scope>test</scope>
</dependency>
Gradle
testImplementation 'org.mock-server:mockserver-testcontainers:7.4.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.
| Helper | What 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.4.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.
The example above drives MockServer over its REST API; or call container.GetClient() for a ready-wired MockServer.Client with a typed fluent API (the package is a transitive dependency).
| Method | What 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().
The example above drives MockServer over its REST API; or call container.getClient() for a ready-wired mockserver-client with a typed fluent API (the package is a dependency of this module).
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.
The example above drives MockServer over its REST API; or call mockserver.get_client() for a ready-wired mockserver client with a typed fluent API (the mockserver-client package is a dependency of this module).
| Method | What 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.12", features = ["blocking"] }
Requires Rust 1.70+ (2021 edition) 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
}
The examples above drive MockServer over its REST API; or call testcontainers_mockserver::client(&container) (or async_client) for a ready-wired mockserver-client with a typed fluent API (the crate is a dependency of this module).
use testcontainers_mockserver::MockServer;
let image = MockServer::new("mockserver-7.4.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.25+ 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.
The example above drives MockServer over its REST API; or construct a mockserver-client-go client from the container's mapped host and port — mockserver.New(host, port) using ctr.Host(ctx) and ctr.ServerPort(ctx) — for a typed fluent API.
Ruby
The testcontainers-mockserver gem integrates with the Testcontainers for Ruby library. It starts a mockserver/mockserver container, waits for readiness, and exposes connection helpers plus a ready-wired mockserver-client instance.
# Gemfile
gem "testcontainers-mockserver", group: :test
Requires Ruby >= 3.0 and Docker.
require "testcontainers/mockserver"
container = Testcontainers::MockServerContainer.new.start
# A ready-wired MockServer client pointed at the mapped host/port
client = container.client
client
.when(MockServer::HttpRequest.request(path: "/hello"))
.respond(MockServer::HttpResponse.response(status_code: 200, body: "world"))
# Point the system under test at the container endpoint
container.endpoint # => "http://localhost:49152"
container.stop # also closes the cached client
Helpers client (a wired MockServer::Client), endpoint / secure_endpoint (HTTP / HTTPS on the same port), server_port, and host expose the connection details. The block form MockServerContainer.new.use { |c| ... } auto-stops the container.
| Method | What 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) | Mount a startup expectations JSON file loaded at container start. |
PHP
The mock-server/mockserver-testcontainers package integrates with the Testcontainers for PHP library. It starts a mockserver/mockserver container, waits for readiness, and exposes connection helpers plus a ready-wired mock-server/mockserver-client instance.
composer require --dev mock-server/mockserver-testcontainers
Requires PHP >= 8.1 and Docker.
use MockServer\Testcontainers\MockServerContainer;
use MockServer\HttpRequest;
use MockServer\HttpResponse;
$container = (new MockServerContainer())->start();
// A ready-wired MockServer client pointed at the mapped host/port.
// (getMockServerClient() is the PHP analogue of Java's getClient() — the
// inherited getClient() name is reserved by Testcontainers for the Docker client.)
$client = $container->getMockServerClient();
$client
->when(HttpRequest::request()->method('GET')->path('/hello'))
->respond(HttpResponse::response()->statusCode(200)->body('world'));
// Point the system under test at the container endpoint
$container->getEndpoint(); // "http://localhost:49152"
$container->stop();
Use getEndpoint() / getSecureEndpoint() for the HTTP / HTTPS base URL, getServerPort() for the mapped port, and getMockServerClient() for the wired client.
| Method | What it does |
|---|---|
| withServerPort(int) | Override the listen port inside the container. |
| withLogLevel(string) | Set MOCKSERVER_LOG_LEVEL. |
| withMockServerProperty(key, value) | Set any MockServer configuration property by its env-var name. |
| withInitializationJson(path) | Copy a startup expectations JSON file into the container and load it at start. |
Standard Testcontainers GenericContainer helpers (withNetwork, withEnvironment, …) are also available via inheritance.
For more information see Fast Tests: Startup Time, Memory and Reuse, Running MockServer via Testcontainers and the available MockServer clients.