Skip to main content
The Java client gives you two ways to interact with MockServer: connect to an already-running instance, or start MockServer in-process and connect to it in one step.

Installation

Add the mockserver-netty-no-dependencies artifact to your project:

Choosing a client class

MockServerClient

MockServerClient connects to a MockServer instance that is already running. Use this when MockServer is started separately — for example, via Docker, the Maven plugin, or the CLI.

ClientAndServer

ClientAndServer starts a MockServer instance in the current JVM process and returns a client connected to it. This is the most convenient option for unit and integration tests.
Use PortFactory.findFreePort() to avoid port conflicts when multiple test suites run in parallel.

Static imports

The Java API relies on static factory methods. Add these imports to every test file that uses the fluent builder API:

Creating expectations

Call .when(request) to match a request, then chain .respond(response) to define the action.
To limit how many times the expectation fires, pass a Times constraint:

Connecting over TLS

Pass .withSecure(true) to send client requests over HTTPS:

Verifying requests

Verify by count

Check that a request was received a specific number of times:

Verify a sequence

Pass multiple request matchers to .verify() to assert that they were received in order:
MockServer confirms that each request in the list was received at least once, in that exact order.

Retrieving recorded requests

Retrieve all requests MockServer has received that match a given matcher:
Retrieve matching request-response pairs:

Clearing and resetting state

Clear matching state

Remove expectations and recorded requests that match a specific request pattern:
Clear only the log (recorded requests and responses), leaving expectations intact:
Clear only expectations, leaving the request log intact:

Reset all state

Remove all expectations and the entire request log:

Test framework integration

JUnit 4 — @Rule

Add the mockserver-junit-rule-no-dependencies dependency:
Use the MockServerRule in your test class. MockServer starts before any test runs and stops after all tests complete. Any field of type MockServerClient is automatically injected:

JUnit 5 — @ExtendWith

Add the mockserver-junit-jupiter-no-dependencies dependency:
Use @ExtendWith(MockServerExtension.class). MockServer injects a ClientAndServer (or MockServerClient) via constructor or method parameter resolution:
Omit @MockServerSettings to let MockServer pick a free port automatically.

Standalone test class with @BeforeClass

If you prefer not to use a rule or extension, use ClientAndServer.startClientAndServer in a static setup method:

Binding additional ports

Instruct a running MockServer to start listening on additional ports: