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) {
// ...
}
}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 packaging manager for OS X (i.e. Apple Mac), can be used to install MockServer, as follows:
brew install mockserver
The MockServer formula in Homebrew performs the following actions:
Once the MockServer has been installed by Homebrew it is available from any command shell as the mockserver command
The mockserver command supports the following options:
mockserver -serverPort <port> [-proxyRemotePort <port>] [-proxyRemoteHost <hostname>] [-logLevel <level>] [-jvmOptions <system parameters>]
valid options are:
-serverPort <port> The HTTP, HTTPS, SOCKS and HTTP CONNECT
port(s) for both mocking and proxying
requests. Port unification is used to
support all protocols for proxying and
mocking on the same port(s). Supports
comma separated list for binding to
multiple ports.
-proxyRemotePort <port> Optionally enables port forwarding mode.
When specified all requests received will
be forwarded to the specified port, unless
they match an expectation.
-proxyRemoteHost <hostname> Specified the host to forward all proxy
requests to when port forwarding mode has
been enabled using the proxyRemotePort
option. This setting is ignored unless
proxyRemotePort has been specified. If no
value is provided for proxyRemoteHost when
proxyRemotePort has been specified,
proxyRemoteHost will default to \"localhost\".
-logLevel <level> Optionally specify log level using SLF4J levels:
TRACE, DEBUG, INFO, WARN, ERROR, OFF or Java
Logger levels: FINEST, FINE, INFO, WARNING,
SEVERE or OFF. If not specified default is INFO
-jvmOptions <level> Specified generic JVM options or system properties.
i.e. mockserver -logLevel INFO -serverPort 1080,1081 -proxyRemotePort 80 -proxyRemoteHost www.mock-server.com
For example run the MockServer, as follows:
mockserver -logLevel INFO -serverPort 1080
MockServer can be run directly from the command line using java directly as follow:
download mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar from Maven Central
java -jar <path to mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar> -serverPort <port>
The command line supports the following options:
java -jar <path to mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar> -serverPort <port> [-proxyRemotePort <port>] [-proxyRemoteHost <hostname>] [-logLevel <level>]
valid options are:
-serverPort <port> The HTTP, HTTPS, SOCKS and HTTP CONNECT
port(s) for both mocking and proxying
requests. Port unification is used to
support all protocols for proxying and
mocking on the same port(s). Supports
comma separated list for binding to
multiple ports.
-proxyRemotePort <port> Optionally enables port forwarding mode.
When specified all requests received will
be forwarded to the specified port, unless
they match an expectation.
-proxyRemoteHost <hostname> Specified the host to forward all proxy
requests to when port forwarding mode has
been enabled using the proxyRemotePort
option. This setting is ignored unless
proxyRemotePort has been specified. If no
value is provided for proxyRemoteHost when
proxyRemotePort has been specified,
proxyRemoteHost will default to \"localhost\".
-logLevel <level> Optionally specify log level using SLF4J levels:
TRACE, DEBUG, INFO, WARN, ERROR, OFF or Java
Logger levels: FINEST, FINE, INFO, WARNING,
SEVERE or OFF. If not specified default is INFO
i.e. java -jar ./mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar -serverPort 1080 -proxyRemotePort 80 -proxyRemoteHost www.mock-server.com
For example:
java -jar ~/Downloads/mockserver-netty-no-dependencies-{{ site.mockserver_version }}.jar -serverPort 1080,1081 -logLevel INFO
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 argument logLevel can be used to set the log level, as shown above. It is also possible to further customise where loggers send log events by overriding the default logging configuration.
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)
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 11 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