Maven Plugin

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>5.6.0</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>5.6.0</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>2.17</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

To stop a forked instance of MockServer running on the same machine:

mvn mockserver:stopForked

The stopForked goal does 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:

 

Client API  -  starting and stopping

Use the client API to run MockServer programmatically.

First add the following maven dependency:

<!-- mockserver -->
<dependency>
     <groupId>org.mock-server</groupId>
     <artifactId>mockserver-netty</artifactId>
     <version>5.6.0</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 BookPageIntegrationTest that demonstrates a fully working example.

 

Running MockServer via a JUnit @Rule

MockServer can be run using the MockServerRule. The MockServerRule starts MockServer (which now includes the proxy) 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-netty</artifactId>
    <version>5.6.0</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 per TestSuite);
/**
 * 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
 * @param port the HTTP(S) port for the proxy
 *                     if true a single MockServer is created per JVM
 *                     if false one instance per test class is created
 */
public MockServerRule(Object target, boolean per TestSuite, Integer... ports);
 

Running From Command Line

MockServer can be run from the command line in the following ways:

 

Running From Command Line - Using Homebrew

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:

  1. installed the binaries and scripts
  2. creates the log directory
  3. add the scripts to the PATH variable

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 as TRACE, DEBUG,
                                 INFO, WARN, ERROR 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

Logging

When MockServer is installed via Homebrew a log directory is created at /usr/local/var/log/mockserver. All logs are written into this directory, this includes normal application logs, which are are written in /usr/local/var/log/mockserver/mockserver.log, and request logs, which are written into /usr/local/var/log/mockserver/mockserver_request.log (when a dumpToLog request is received).

The amount of logs written into the application log /usr/local/var/log/mockserver/mockserver.log can be controlled using the -logLevel command as detailed above.

 

Running From Command Line - Using Java

MockServer can be run directly from the command line using java directly as follow:

  1. download mockserver-netty-5.6.0-jar-with-dependencies.jar from Maven Central

  2. java -jar <path to mockserver-netty-5.6.0-jar-with-dependencies.jar> -serverPort <port>

The command line supports the following options:

java -jar <path to mockserver-jetty-jar-with-dependencies.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 as TRACE, DEBUG,
                                 INFO, WARN, ERROR or OFF. If not specified
                                 default is INFO

i.e. java -jar ./mockserver-jetty-jar-with-dependencies.jar -serverPort 1080 -proxyRemotePort 80 -proxyRemoteHost www.mock-server.com

For example:

java -jar ~/Downloads/mockserver-netty-5.6.0-jar-with-dependencies.jar -serverPort 1080,1081 -logLevel INFO

All interactions with the MockServer are logged including setting up expectations, matching expectations, clearing expectations and verifying requests. The when running from the command line, Maven plugin, npm module or Grunt plugin the log is written to a file called mockserver.log in the current working directory where the MockServer is running. This log 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 specify a custom logback configuration file to override the default MockServer or MockServer Proxy logging settings. An example logback configuration file is available in github.

A custom logback configuration file can be specified using the logback.configurationFile system property with an absolute or relative file path or a classpath, as follows:

java -Droot.logLevel=WARN -Dlogback.configurationFile=example_logback.xml -jar ~/Downloads/mockserver-netty-5.6.0-jar-with-dependencies.jar -serverPort 1080,1081 -logLevel INFO

A custom logback configuration file will also be automatically picked up if it is called logback.xml and is in the root of the classpath, however, the jar-with-dependencies already contains a logback.xml file, so to override this, the overriding logback.xml file must be higher (i.e. earlier) in the classpath.

Disabling Logging

To disable logging the following system properties can be used:

If logging is disabled then no log file will be created. This is because the log files are only created when the first item is written to the log file.

 

Running From Command Line - Using Maven Plugin

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:5.6.0: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:5.6.0:stopForked

For more information on the mockserver-maven-plugin see the section on MockServer Maven Plugin

 

Web Archive (WAR)

To run as a WAR deployed on any JEE web server:

  1. download mockserver-war-5.6.0.war from Maven Central
  2. deploy mockserver-war-5.6.0.war to 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)
 

NPM Module & MockServer Grunt Plugin

{% include_subpage ../mock_server/_includes/running_npm_module.html %}  

Docker Container

{% include_subpage ../mock_server/_includes/running_docker_container.html %}  

Build & Run From Source

MockServer is now only built using maven as the use of gradle caused problems with the Travis CI environment so the gradle build was removed.

First clone the repository as follows:

git clone https://github.com/jamesdbloom/mockservice.git
cd mockserver

Next use maven to build an executable jar containing all dependencies as follows:

mvn clean package

This will produce a jar file under the target directory called, as follows:

mockserver-netty/target/mockserver-netty-5.6.0-jar-with-dependencies.jar

Run MockServer then using the executable jar as per the instruction above in Running From The Command Line