To run MockServer as part of your build add the following plugin to your pom.xml:
<plugin>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-maven-plugin</artifactId>
<version>{{ site.mockserver_version }}</version>
<configuration>
<serverPort>1080</serverPort>
<logLevel>DEBUG</logLevel>
<initializationClass>org.mockserver.maven.ExampleInitializationClass</initializationClass>
</configuration>
<executions>
<execution>
<id>process-test-classes</id>
<phase>process-test-classes</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>verify</id>
<phase>verify</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
This will start MockServer during the process-test-classes phase and will stop MockServer during the verify phase. For more details about Maven build phases see: Introduction to the Build Lifecycle.
This ensures that any integration tests you run during the test or integration-test phases can use MockServer on the port specified.
It is also possible to run MockServer as a forked JVM using the runForked and stopForked goals as follows:
<plugin>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-maven-plugin</artifactId>
<version>{{ site.mockserver_version }}</version>
<configuration>
<serverPort>1080</serverPort>
<logLevel>DEBUG</logLevel>
</configuration>
<executions>
<execution>
<id>process-test-classes</id>
<phase>process-test-classes</phase>
<goals>
<goal>runForked</goal>
</goals>
</execution>
<execution>
<id>verify</id>
<phase>verify</phase>
<goals>
<goal>stopForked</goal>
</goals>
</execution>
</executions>
</plugin>
Stop MockServer Even When Tests Fail
If you use the runForked goal as above and the test phase fails (because a test has failed) MockServer will not be stopped as Maven does not run any more phases after a phase has failed. In the case above the verify phase is not run if a test fails so the forked MockServer will not be stopped.
If you want to ensure MockServer is stopped even when there are test failures make sure you use start and stop goals as these run MockServer on a separate thread that is stopped however maven exits (even if a test fails).
Alternatively a TestListener can be used with maven-surefire-plugin to ensure that MockServer is stopped even when a test fails, as follows:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.5</version>
<configuration>
<properties>
<property>
<name>listener</name>
<value>org.mockserver.maven.StopMockServerTestListener</value>
</property>
</properties>
</configuration>
</plugin>
The Maven plugin can also be used from the command line to start and stop MockServer, as follows:
To run MockServer synchronously and block:
mvn mockserver:run
To run MockServer asynchronously as a forked JVM:
mvn mockserver:runForked
Or:
mvnw org.mock-server:mockserver-maven-plugin:{{ site.mockserver_version }}:runForked -DserverPort=1080
To stop a forked instance of MockServer running on the same machine:
mvn mockserver:stopForked
Or:
mvnw org.mock-server:mockserver-maven-plugin:{{ site.mockserver_version }}:stopForked -DserverPort=1080
The stopForked goal assumes that MockServer is running on the same physical machine as it uses 127.0.0.1 to communicate with MockServer stop socket.
The Maven plugin has the following goals:
The Maven plugin can be configured with the following properties:
Use the client API to run or interact with MockServer programmatically.
For more details about the different dependency versions see the page on Maven Central
For example add the following maven dependency:
<!-- mockserver -->
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty-no-dependencies</artifactId>
<version>{{ site.mockserver_version }}</version>
</dependency>
To start the server or proxy create a client, for example by using one of the start factory methods ClientAndServer.startClientAndServer as follows:
Add includes:
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
Add fields:
private ClientAndServer mockServer;
Use factory method to start server and client when appropriate, for example in @Before method:
@Before
public void startMockServer() {
mockServer = startClientAndServer(1080);
}
Stop server and client when appropriate, for example in @After method:
@After
public void stopMockServer() {
mockServer.stop();
}
The mockserver-example project contains an example test called BooksPageIntegrationTest that demonstrates a fully working example.
MockServer can be run using the MockServerRule. The MockServerRule starts MockServer (for both mocking and proxying) on a free port before the any test runs and stops MockServer after all tests have completed.
An instance of MockServerClient is assigned to any field in the unit test of type org.mockserver.client.MockServerClient. Alternatively an instance of MockServerClient can be retrieved from the MockServerRule using the method getClient().
@Rule
public MockServerRule mockServerRule = new MockServerRule(this);
private MockServerClient mockServerClient;
The MockServerRule can be added to your project by including the following maven dependency:
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-junit-rule-no-dependencies</artifactId>
<version>{{ site.mockserver_version }}</version>
</dependency>
Any test method can now use the mockServerClient field to create expectation or verify requests.
The MockServerRule has the following constructors:
/**
* Start MockServer prior to test execution and stop MockServer after the tests have completed.
* This constructor dynamically allocates a free port for MockServer to use.
*
* @param target an instance of the test being executed
*/
public MockServerRule(Object target);
/**
* Start MockServer prior to test execution and stop MockServer after the tests have completed.
* This constructor dynamically allocates a free port for MockServer to use.
*
* @param target an instance of the test being executed
* @param perTestSuite indicates how many instances of MockServer are created
* if true a single MockServer is created per JVM
* if false one instance per test class is created
*/
public MockServerRule(Object target, boolean perTestSuite);
/**
* Start the proxy prior to test execution and stop the proxy after the tests have completed.
* This constructor dynamically create a proxy that accepts HTTP(S) requests on the specified port
*
* @param target an instance of the test being executed
* @param port the HTTP(S) port for the proxy
*/
public MockServerRule(Object target, Integer... ports);
/**
* Start the proxy prior to test execution and stop the proxy after the tests have completed.
* This constructor dynamically create a proxy that accepts HTTP(S) requests on the specified port
*
* @param target an instance of the test being executed
* @param perTestSuite indicates how many instances of MockServer are created
* if true a single MockServer is created per JVM
* if false one instance per test class is created
* @param port the HTTP(S) port for the proxy
*/
public MockServerRule(Object target, boolean perTestSuite, Integer... ports);
MockServer can be run using the Test Extension MockServerExtension. The MockServerExtension starts MockServer (for both mocking and proxying) before the any test runs and stops MockServer after all tests have completed.
The port(s) MockServer uses can be controlled using MockServerSettings
An instance of MockServerClient or ClientAndServer is injected into any method using Parameter Resolution this includes: constructors, lifecycle methods (like @BeforeEach / @BeforeAll), or test methods.
The MockServerExtension Test Extension can be added to your project by including the following maven dependency:
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-junit-jupiter-no-dependencies</artifactId>
<version>{{ site.mockserver_version }}</version>
</dependency>
Warning: @MockServerSettings already includes @ExtendWith(MockServerExtension.class) internally. Do not add both annotations to the same test class — doing so will cause MockServer to start twice, resulting in port conflicts or unexpected behaviour. Use @ExtendWith(MockServerExtension.class) alone for default settings, or @MockServerSettings alone when you need to configure ports or other options.
The following code examples show how to use the MockServerExtension Test Extension.
@ExtendWith(MockServerExtension.class)
@MockServerSettings(ports = {8787, 8888})
class ExampleTestClass {
private final ClientAndServer client;
public ExampleTestClass(ClientAndServer client) {
this.client = client;
}
@Test
void testSomething() {
// ...
}
}@ExtendWith(MockServerExtension.class)
class ExampleTestClass {
private final ClientAndServer client;
public ExampleTestClass(ClientAndServer client) {
this.client = client;
}
@Test
void testSomething() {
// ...
}
}@ExtendWith(MockServerExtension.class)
class ExampleTestClass {
private MockServerClient client;
@BeforeEach
public void beforeEachLifecycleMethod(MockServerClient client) {
this.client = client;
}
@Test
void testSomething() {
// ...
}
}@ExtendWith(MockServerExtension.class)
class ExampleTestClass {
@Test
void testSomething(MockServerClient client) {
// ...
}
}By default a shared MockServer instance accumulates expectations across all tests in the class. Add resetBeforeEach = true to @MockServerSettings to have MockServer automatically reset (clear all expectations, recorded requests, and logs) before each test method runs — without you having to call client.reset() yourself.
@MockServerSettings(ports = {1080}, resetBeforeEach = true)
class IsolatedTestClass {
private final MockServerClient client;
public IsolatedTestClass(MockServerClient client) {
this.client = client;
}
@Test
void firstTest() {
// MockServer is clean — no expectations from any earlier test
client.when(request().withPath("/hello"))
.respond(response().withBody("world"));
// ...
}
@Test
void secondTest() {
// MockServer is clean again — expectations from firstTest are gone
client.when(request().withPath("/goodbye"))
.respond(response().withBody("farewell"));
// ...
}
}
The reset fires in BeforeEachCallback, which runs before any @BeforeEach methods in the test class. When combined with perTestSuite = true the same shared server is reset before each test across all test classes in the suite.
MockServer can be run using @MockServerTest. The mockserver-spring-test-listener dependency registers a Spring TestExecutionListener which starts MockServer on a free port if the test class is annotated with @MockServerTest. MockServer is reset after each test and closed after all tests via a shutdown hook.
As the MockServer instance is shared between all test classes @MockServerTest does not support parallel test execution, unless each test uses a unique value in each request matcher.
The TestExecutionListener with @MockServerTest can be added to your project by including the following maven dependency:
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-spring-test-listener-no-dependencies</artifactId>
<version>{{ site.mockserver_version }}</version>
</dependency>
An instance of MockServerClient is assigned to any field in the unit test of type org.mockserver.client.MockServerClient.
@MockServerTest
@RunWith(SpringRunner.class)
public class ExampleSpringTestListenerTestWithClientInjection {
private MockServerClient mockServerClient;
@Test
public void testSomething() {
// test code
}
}
If you want to configure a client (Spring Bean) to use MockServer you can create a test property with ${mockServerPort} placeholder. This is replaced by the chosen free port for MockServer.
@RunWith(SpringRunner.class)
@MockServerTest("server.url=http://localhost:${mockServerPort}/path")
@ContextConfiguration(classes = MockServerTestFullSampleTest.Config.class)
public class ExampleSpringTestListenerTestWithUrlInjection {
static class Client {
@Value("${server.url}")
private URI serverUrl;
private final RestTemplate restTemplate = new RestTemplate();
@Nullable
public <T> T getResult(String path, Class<T> responseType) {
return restTemplate.getForObject(serverUrl + path, responseType);
}
}
static class Config {
@Bean
public Client client() {
return new Client();
}
}
@Autowired
private Client client;
private MockServerClient mockServerClient;
@Test
public void testSomething() {
// test code
}
}
Properties prefixed with mockserver. are applied to the MockServer Configuration object, allowing declarative configuration of MockServer directly in the annotation. All other properties are injected into the Spring Environment as test properties (with ${mockServerPort} substitution). This enables setting any configuration property such as initializationClass, logLevel, maxExpectations, etc. without needing separate system property setup.
Note: Because the MockServer instance is shared across all test classes, mockserver.* configuration properties from the first @MockServerTest class to run are used. If multiple test classes specify different mockserver.* properties, only the first class's configuration takes effect.
@RunWith(SpringRunner.class)
@MockServerTest({
"server.url=http://localhost:${mockServerPort}/path",
"mockserver.initializationClass=org.mockserver.server.initialize.ExpectationInitializerExample",
"mockserver.logLevel=WARN"
})
public class ExampleSpringTestListenerTestWithConfiguration {
private MockServerClient mockServerClient;
@Test
public void testSomething() {
// expectations from ExpectationInitializerExample are available immediately
}
}
The free port itself is also added as test property and can be retrieved with @MockServerPort.
@MockServerTest
@RunWith(SpringRunner.class)
public class ExampleSpringTestListenerTestWithPortInjection {
@MockServerPort
Integer mockServerPort;
@Test
public void testSomething() {
// test code
}
}
MockServer can be run from the command line in the following ways:
Homebrew, a package manager for macOS and Linux, can be used to install MockServer, as follows:
brew install mockserver
The MockServer formula in Homebrew performs the following actions:
Once MockServer has been installed by Homebrew it is available from any command shell as the mockserver command.
mockserver run -p 1080
MockServer can be run directly from the command line using java as follows:
download mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar from Maven Central
java -jar <path to mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar> run -p <port>
The MockServer CLI uses subcommands. The most common is run, which starts MockServer and accepts expectations and proxied traffic on the specified port. You can omit the subcommand name entirely — bare flags like -p 1080 are treated as run automatically.
| Subcommand | What it does | Example |
|---|---|---|
| run | Start MockServer in mock and/or proxy mode (default subcommand) | mockserver run -p 1080 |
| proxy | Start MockServer as a pure forwarding proxy — shorthand for run --proxy-to | mockserver proxy --to api.example.com:8080 -p 1080 |
| openapi | Start MockServer and automatically create expectations from an OpenAPI spec | mockserver openapi ./petstore.yaml -p 1080 |
| import | Load expectations from a JSON file into an already-running MockServer | mockserver import ./expectations.json -p 1080 |
| demo | Start MockServer pre-loaded with a small set of example expectations and print a getting-started URL and sample curl — the fastest way to try MockServer | mockserver demo -p 1080 |
| version | Print MockServer version and exit | mockserver version |
| help | Print usage for the top command or any subcommand | mockserver help run |
| Option | Description | Configuration property |
|---|---|---|
| -p, --port <port> | Port(s) to listen on. Comma-separated list to bind multiple ports, e.g. 1080,1081. Port unification means HTTP, HTTPS, and all proxy protocols share the same port. | mockserver.serverPort |
| --proxy-to <target> | Forward unmatched requests to the given target. Enables port-forwarding (proxy) mode. Accepts host:port, https://host[:port] (port 443 inferred from scheme), or http://host[:port] (port 80 inferred). A bare hostname with no port and no http(s):// scheme is rejected with an error. | mockserver.proxyRemoteHost + mockserver.proxyRemotePort |
| --openapi <specUrlOrPath> | Initialize expectations from an OpenAPI spec on startup. Accepts a file path or URL. | mockserver.initializationOpenAPIPath |
| --init <fileOrGlob> | Initialize expectations from a JSON file or glob pattern on startup. | mockserver.initializationJsonPath |
| --watch | Watch the initializer/expectations file(s) (from --init / --openapi) and live-reload expectations when they change, without restarting MockServer (~5s poll). Handy for editing expectations while the server runs. Also available as MOCKSERVER_WATCH_INITIALIZATION_JSON=true or -Dmockserver.watchInitializationJson=true. | mockserver.watchInitializationJson |
| --persist <file> | Enable expectation persistence and write expectations to the given file. MockServer reloads the file on restart. | mockserver.persistExpectations + mockserver.persistedExpectationsPath |
| -l, --log-level <level> | Set the log level. Accepts SLF4J levels: TRACE, DEBUG, INFO, WARN, ERROR, OFF, or Java Logger levels: FINEST, FINE, INFO, WARNING, SEVERE, OFF. Default: INFO. | mockserver.logLevel |
| --dev | Enable developer-friendly defaults for laptop and test-suite workloads. Sets maxLogEntries=1000 and maxExpectations=1000 (reducing memory usage). Any explicit configuration (system property, environment variable, or properties file) overrides the dev-mode defaults. Also available as MOCKSERVER_DEV_MODE=true or -Dmockserver.devMode=true. | mockserver.devMode |
| --validate-openapi <spec> | Validate every forwarded/proxied request and its upstream response against the given OpenAPI spec. Accepts a URL, file path, or inline JSON/YAML payload. Violations are logged as OPENAPI_REQUEST_VALIDATION_FAILED and OPENAPI_RESPONSE_VALIDATION_FAILED events. By default, traffic is not blocked — combine with --validate-enforce to reject non-conformant traffic. | mockserver.validateProxyOpenAPISpec |
| --validate-enforce | When combined with --validate-openapi, reject requests that violate the spec with a 400 status code, and replace non-conformant upstream responses with a 502. Without this flag, violations are report-only (logged but traffic flows unmodified). | mockserver.validateProxyEnforce |
| --print-config | Print the effective configuration and exit. Each known property is listed as name = value [source], where source is the tier that supplied the value — system-property, properties-file, environment-variable, default, or runtime-set (a value applied at runtime in Java code) — so you can see exactly which value MockServer will use and where it came from. Properties left at their built-in default show (default). Sensitive values (passwords, API keys, tokens, secrets, private keys, credentials) are redacted as ***REDACTED***. The same report is available at runtime as JSON from the authenticated GET /mockserver/config control-plane endpoint. | — |
| -h, --help | Print usage and exit. | — |
| Option | Required | Description |
|---|---|---|
| --to <target> | Yes | Forward all unmatched requests to this target. Accepts host:port or a full URL such as https://api.example.com (port 443 inferred) or http://api.example.com (port 80 inferred). A bare hostname with no port and no http(s):// scheme is rejected with an error. |
| -p, --port <port> | No | Port(s) to listen on. |
| -l, --log-level <level> | No | Log level (see above). |
| --validate-openapi <spec> | No | Validate forwarded/proxied traffic against the given OpenAPI spec (URL, file path, or inline payload). Violations are logged; combine with --validate-enforce to block non-conformant traffic. |
| --validate-enforce | No | When combined with --validate-openapi, block non-conformant traffic (400 for requests, 502 for responses). |
| Argument / Option | Required | Description |
|---|---|---|
| <specUrlOrPath> | Yes (positional) | OpenAPI spec file path or URL. |
| -p, --port <port> | No | Port(s) to listen on. |
| -l, --log-level <level> | No | Log level (see above). |
The import subcommand connects to an already-running MockServer and loads expectations into it from a JSON file. It does not start a server — start one first (e.g. mockserver run -p 1080), then import. The file may be a single expectation object or an array of expectations, the same format produced by the --persist flag, the dashboard export, or the active-expectations retrieve endpoint. Each expectation is created, or updated if its id matches an existing one. If the file is missing/invalid or the server is unreachable, a clear error is printed and the command exits with a non-zero status.
| Argument / Option | Required | Description |
|---|---|---|
| <file> | Yes (positional) | Path to a JSON file containing a single expectation or an array of expectations. |
| -p, --port <port> | Yes | Port of the running MockServer to load the expectations into. |
| -H, --host <host> | No | Host of the running MockServer. Default: localhost. |
The demo subcommand starts MockServer pre-loaded with a small set of example expectations (GET /hello and GET /users/{id}) and prints a getting-started URL, the dashboard URL, and a sample curl command. It is the fastest way to see MockServer responding to requests without writing any expectations first. It accepts the same -p, --port (default 1080), -l, --log-level, and -D<key>=<value> options as run. After starting, try curl http://localhost:1080/hello.
Start MockServer on port 1080:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar run -p 1080
Start MockServer on two ports:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar run -p 1080,1081
Start MockServer and forward unmatched requests to an upstream API:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar run -p 1080 --proxy-to api.example.com:8080
Start MockServer, load expectations from an OpenAPI spec, and persist any additional expectations set via the API:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar run -p 1080 \
--openapi ./petstore.yaml \
--persist ./expectations.json
Load expectations from a JSON file into a server that is already running on port 1080:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar import ./expectations.json -p 1080
Start a demo server pre-loaded with example expectations (then try curl http://localhost:1080/hello):
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar demo -p 1080
Start MockServer initialized from a JSON file and live-reload expectations whenever that file changes, with no restart:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar run -p 1080 --init ./expectations.json --watch
Start MockServer as a plain forwarding proxy (shorthand form, explicit port):
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar proxy --to api.example.com:8080 -p 1080
Start MockServer as a plain forwarding proxy using a scheme URL — port 443 is inferred from https://:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar proxy --to https://api.example.com -p 1080
The same with run --proxy-to:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar run -p 1080 --proxy-to https://api.example.com
Note: a bare hostname such as --proxy-to api.example.com (no port, no scheme) is rejected. Use api.example.com:8080 or a scheme URL such as https://api.example.com.
Combine --validate-openapi and --validate-enforce to turn MockServer into a contract-validating proxy that checks every request and response against an OpenAPI spec. This is useful in CI to catch API drift early, or in a staging environment to find clients that send non-conformant requests before they reach production.
Step 1 — Report-only mode: start without --validate-enforce. MockServer forwards all traffic unchanged and logs any violations as OPENAPI_REQUEST_VALIDATION_FAILED and OPENAPI_RESPONSE_VALIDATION_FAILED log events. Nothing is blocked, so existing clients are unaffected:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar proxy --to https://api.example.com -p 1080 \
--validate-openapi ./openapi-spec.yaml
Violations appear in the MockServer log (and in the dashboard Log Messages panel) as OPENAPI_REQUEST_VALIDATION_FAILED or OPENAPI_RESPONSE_VALIDATION_FAILED events with the path, method, violation details, and schema location.
Step 2 — Enforce mode: add --validate-enforce to reject non-conformant traffic. A request that violates the spec receives a 400 response; an upstream response that violates the spec is replaced with a 502:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar proxy --to https://api.example.com -p 1080 \
--validate-openapi ./openapi-spec.yaml \
--validate-enforce
Notes:
Start MockServer and pre-load expectations from a JSON file:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar run -p 1080 --init ./expectations.json
All interactions with the MockServer are logged, including setting up expectations, matching expectations, clearing expectations, and verifying requests. This log information can be particularly helpful when trying to debug why a test is failing or expectations are not being matched.
The --log-level flag can be used to set the log level, as shown in the options table above. It is also possible to further customise where loggers send log events by overriding the default logging configuration.
All command-line flags from earlier versions of MockServer continue to work. You do not need to update existing scripts or Docker commands.
| Legacy flag | New equivalent |
|---|---|
| -serverPort <port> | run -p <port> |
| -proxyRemotePort <port> | run --proxy-to host:<port> |
| -proxyRemoteHost <hostname> | run --proxy-to <hostname>:port |
| -logLevel <level> | run -l <level> |
For example, this legacy command continues to work unchanged:
java -jar mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar -serverPort 1080 -proxyRemotePort 80 -proxyRemoteHost www.mock-server.com -logLevel WARN
MockServer resolves configuration from multiple sources. The order of precedence, from highest to lowest, is:
This means that a flag passed on the command line always overrides the same setting from an environment variable or properties file. For a full list of configuration properties and their environment variable names, see the configuration properties page.
MockServer can be run directly from the command line and using the mockserver-maven-plugin as follow:
mvn -Dmockserver.serverPort=1080 -Dmockserver.logLevel=INFO org.mock-server:mockserver-maven-plugin:{{ site.mockserver_version }}:runForked
When run from the command line the Maven plugin can be configured with the following properties:
The runForked goal of the mockserver-maven-plugin will fork a JVM process containing the Netty based MockServer. To stop the forked JVM process use the stopForked goal, as follows:
mvn -Dmockserver.serverPort=1080 org.mock-server:mockserver-maven-plugin:{{ site.mockserver_version }}:stopForked
For more information on the mockserver-maven-plugin see the section on MockServer Maven Plugin
To run as a WAR deployed on any JEE web server:
WAR Context Path
The WAR context path is ignored from all request matching for path.
The MockServerClient constructor includes an argument for the context path that the WAR has been deployed to, as follows:
public MockServerClient(String host, int port, String contextPath)
Most MockServer client libraries can download and launch a local MockServer instance automatically — no Java installation and no Docker required. Each client downloads a self-contained platform bundle that includes a trimmed JVM runtime, the MockServer server, and a launcher script. The bundle is fetched from the GitHub Release, verified against its published SHA-256 checksum, and cached per-user so subsequent launches are instant.
| Client | Language | Launch API |
|---|---|---|
| mockserver-node | Node.js | npx -p mockserver-node mockserver run -p 1080 or ensureBinary(version) / runBinary(version, args) |
| mockserver-client | Python | start(port=1080) / ensure_binary() |
| mockserver-client | Ruby | MockServer::BinaryLauncher.start(port: 1080) / .ensure_launcher |
| mockserver-client-go | Go | mockserver.StartServer(1080, "", nil) / mockserver.EnsureBinary(version, nil) |
| MockServerClient | .NET | MockServerBinaryLauncher.Start(port: 1080) / .EnsureBinary() |
| mockserver-client | Rust | launcher::start(1080) / launcher::ensure_launcher() |
| PHP | PHP | Not supported — start MockServer via Docker, the executable JAR, or another client’s launcher. |
Each bundle is named mockserver-<version>-<os>-<arch>.tar.gz (or .zip on Windows), where:
linux, darwin, or windowsx86_64 or aarch64The bundle is a jlink-assembled custom JVM image — it runs on any machine with a compatible OS and CPU, with no external Java dependency.
All client launchers honour the same set of environment variables for customisation:
| Variable | Purpose |
|---|---|
MOCKSERVER_BINARY_BASE_URL | Override the download base URL. Use this to point at a corporate mirror or an air-gapped artifact store instead of GitHub. |
MOCKSERVER_BINARY_CACHE | Override the per-user cache directory. Default: ~/.cache/mockserver/binaries (Unix) or %LOCALAPPDATA%\mockserver\binaries (Windows). |
MOCKSERVER_SKIP_BINARY_DOWNLOAD | Set to any value to prevent the launcher from downloading. If no cached binary exists, the launcher fails immediately. Useful in CI with a pre-seeded cache. |
By default, each client downloads the MockServer version that matches its own package version. You can override this by passing an explicit version to the start/ensure function.
The repository ships task-oriented docker-compose.yml recipes — each is a self-contained directory you can docker compose up with no extra configuration. Clone the repo (or copy a recipe), cd into it, and run:
cd examples/docker-compose/mock-from-openapi
docker compose up
| Recipe | What it does |
|---|---|
| mock-from-openapi | Serve mocks generated automatically from a mounted OpenAPI / Swagger spec. |
| record-replay-proxy | Proxy to an upstream and record traffic to a replayable expectations file. |
| validation-proxy | Proxy to an upstream and validate requests / responses against an OpenAPI spec. |
| chaos-proxy | Proxy to an upstream while injecting latency and intermittent errors. |
More configuration permutations (custom ports, mounted properties files, mTLS, persisted expectations) live in the docker-compose examples folder.
{% include_subpage ../mock_server/_includes/helm_chart.html %}To have a MockServer container started and torn down automatically by your test run, use MockServer with Testcontainers rather than running a long-lived instance yourself.
However you run MockServer, you can preload expectations at startup and persist them across restarts. These work as CLI flags, configuration properties, or environment variables:
| What you want | CLI flag | Environment variable |
|---|---|---|
| Preload expectations from a JSON file or glob | --init <fileOrGlob> | MOCKSERVER_INITIALIZATION_JSON_PATH |
| Preload expectations from an OpenAPI spec | --openapi <specUrlOrPath> | MOCKSERVER_INITIALIZATION_OPENAPI_PATH |
| Persist expectations to a file across restarts | --persist <file> | MOCKSERVER_PERSIST_EXPECTATIONS=true + MOCKSERVER_PERSISTED_EXPECTATIONS_PATH |
For example, with Docker, mount a spec and serve it as a mock:
docker run -p 1080:1080 \
-v $(pwd)/openapi.yaml:/config/openapi.yaml \
-e MOCKSERVER_INITIALIZATION_OPENAPI_PATH=/config/openapi.yaml \
mockserver/mockserver
See Initializing Expectations, Persisting Expectations, and the configuration properties page (each property lists its environment-variable form) for full details.
To get a working mock from real traffic in seconds: open your browser DevTools, record the requests on the Network tab, and Export HAR. Then import that file into a running MockServer — it creates one expectation per recorded entry:
curl -X PUT "http://localhost:1080/mockserver/import?format=har" \
--data-binary @recording.har
The same endpoint also imports Postman collections. See Importing Expectations from HAR & Postman for format detection, options, and examples.
MockServer is written in Java and built using maven. The maven wrapper is used so maven does not need to be installed but Java JDK 17 or higher must be installed.
First clone the repository as follows:
git clone https://github.com/mock-server/mockserver-monorepo.git
cd mockserver-monorepo/mockserver
Next use maven to build an executable jar containing all dependencies as follows:
./mvnw clean package
This will produce an executable jar file under the target directory called, as follows:
mockserver-netty-no-dependencies/target/mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar
Run MockServer then using the executable jar as per the instruction above in Running From The Command Line