To ensure expectations are available as soon as MockServer is started it is possible to use an expectation initializer, there are three options:

Note: all three options require the class or file to be available to the MockServer, i.e. in the local classpath or filesystem. To remotely initialise the MockServer a client is required to connect to the MockServer after it has started and submit one or more expectations.

 

Expectation Initializer Class

MockServer expectations can be initialized when the MockServer starts, using a class, by specified the initializationClass configuration property as described in the Configuration Properties page, for example:

System.setProperty("mockserver.initializationClass", ExpectationInitializerExample.class.getName());
int mockServerPort = new ClientAndServer().getLocalPort();

The class must implement the org.mockserver.server.initialize.ExpectationInitializer interface and have a default constructor with zero arguments, for example:

public class ExpectationInitializerExample implements ExpectationInitializer {
    @Override
    public Expectation[] initializeExpectations() {
        return new Expectation[]{
            new Expectation(
                request()
                    .withPath("/simpleFirst")
            )
                .thenRespond(
                response()
                    .withBody("some first response")
            ),
            new Expectation(
                request()
                    .withPath("/simpleSecond")
            )
                .thenRespond(
                response()
                    .withBody("some second response")
            )
        };
    }
}
 

Expectation Initializer JSON

MockServer expectations can be initialized when the MockServer starts, using a JSON file, by specified the initializationJsonPath configuration property as described in the Configuration Properties page, for example:

java -Dmockserver.initializationJsonPath="org/mockserver/server/initialize/initializerJson.json" -jar ~/Downloads/mockserver-netty-5.11.1-jar-with-dependencies.jar -serverPort 1080 -logLevel INFO

The JSON file can be loaded using a related or absolute path or can be loaded from the classpath.

The JSON file should contain an array of serialised expectations, for example:

[
  {
    "httpRequest": {
      "path": "/simpleFirst"
    },
    "httpResponse": {
      "body": "some first response"
    }
  },
  {
    "httpRequest": {
      "path": "/simpleSecond"
    },
    "httpResponse": {
      "body": "some second response"
    }
  }
]
 

Expectation Initializer JSON File Watcher

If a JSON expectation initializer is specified a file watcher can be enabled that watches for changes in the expectation initializer and updates the expectations when the file is modified.

If enabled the initialization json file will be watched for changes, any changes found will result in expectations being created, remove or updated by matching against their key.

If duplicate keys exist only the last duplicate key in the file will be processed and all duplicates except the last duplicate will be removed.

The order of expectations in the file is the order in which they are created if they are new, however, re-ordering existing expectations does not change the order they are matched against incoming requests.

MOCKSERVER_WATCH_INITIALIZATION_JSON=true \
MOCKSERVER_INITIALIZATION_JSON_PATH=mockserverInitialization.json \
java -jar ~/Downloads/mockserver-netty-5.11.1-jar-with-dependencies.jar -serverPort 1080,1081 -logLevel INFO

or

java \
-Dmockserver.watchInitializationJson=true \
-Dmockserver.initializationJsonPath=mockserverInitialization.json \
-jar ~/Downloads/mockserver-netty-5.11.1-jar-with-dependencies.jar -serverPort 1080,1081 -logLevel INFO
 

Clustering MockServer

MockServer supports a very high request throughput, however if a higher request per second rate is required it is possible to cluster MockServer so that all nodes share expectations.

Although expectations are clustered, currently there is no support for clustering the MockServer log therefore request verifications will only work against the node that received the request.

To create a MockServer cluster all instances need to:

Each node could be configured as follows (adjusting the port as necessary):

MOCKSERVER_WATCH_INITIALIZATION_JSON=true \
MOCKSERVER_INITIALIZATION_JSON_PATH=mockserverInitialization.json \
MOCKSERVER_PERSIST_EXPECTATIONS=true \
MOCKSERVER_PERSISTED_EXPECTATIONS_PATH=mockserverInitialization.json \
java -jar ~/Downloads/mockserver-netty-5.11.1-jar-with-dependencies.jar -serverPort 1080 -logLevel INFO

or

java \
-Dmockserver.watchInitializationJson=true \
-Dmockserver.initializationJsonPath=mockserverInitialization.json \
-Dmockserver.persistExpectations=true \
-Dmockserver.persistedExpectationsPath=mockserverInitialization.json \
-jar ~/Downloads/mockserver-netty-5.11.1-jar-with-dependencies.jar -serverPort 1080 -logLevel INFO
 

Maven Plugin Expectation Initializer Class

If the MockServer is started using the Maven Plugin a initializationClass property can be specified to initialize expectations, when the MockServer starts.

Note: the plugin must be started during the process-test-classes to ensure that the initialization class has been compiled from either src/main/java or src/test/java locations. In addition the initializer can only be used with start and run goals, it will not work with the runForked goal as a JVM is forked with a separate classpath. (required: false, default: false)

The following section from a pom.xml shows how the Maven Plugin can be configured to specify an initializationClass:

<plugin>
    <groupId>org.mock-server</groupId>
    <artifactId>mockserver-maven-plugin</artifactId>
    <version>5.11.1</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>

The class must implement the org.mockserver.client.initialize.PluginExpectationInitializer interface and have a default constructor with zero arguments, for example:

public class ExampleInitializationClass implements ExpectationInitializer {

    @Override
    public void initializeExpectations(MockServerClient mockServerClient) {
        mockServerClient
                .when(
                        request()
                                .withPath("/simpleFirst")
                )
                .respond(
                        response()
                                .withBody("some first response")
                );
        mockServerClient
                .when(
                        request()
                                .withPath("/simpleSecond")
                )
                .respond(
                        response()
                                .withBody("some second response")
                );
    }
}
 

Initialization & Persistence Configuration:

The class (and package) used to initialize expectations in MockServer at startup, if set MockServer will load and call this class to initialise expectations when is starts.

Type: string Default: null

Java Code:

ConfigurationProperties.initializationClass(String initializationClass)

System Property:

-Dmockserver.initializationClass=...

Environment Variable:

MOCKSERVER_INITIALIZATION_CLASS=...

Property File:

mockserver.initializationClass=...

Example:

-Dmockserver.initializationClass="org.mockserver.server.initialize.ExpectationInitializerExample"

The path to the json file used to initialize expectations in MockServer at startup, if set MockServer will load this file and initialise expectations for each item in the file when is starts.

The expected format of the file is a JSON array of expectations, as per the REST API format

Type: string Default: null

Java Code:

ConfigurationProperties.initializationJsonPath(String initializationJsonPath)

System Property:

-Dmockserver.initializationJsonPath=...

Environment Variable:

MOCKSERVER_INITIALIZATION_JSON_PATH=...

Property File:

mockserver.initializationJsonPath=...

Example:

-Dmockserver.initializationJsonPath="org/mockserver/server/initialize/initializerJson.json"

If enabled the initialization json file will be watched for changes, any changes found will result in expectations being created, remove or updated by matching against their key.

If duplicate keys exist only the last duplicate key in the file will be processed and all duplicates except the last duplicate will be removed.

The order of expectations in the file is the order in which they are created if they are new, however, re-ordering existing expectations does not change the order they are matched against incoming requests.

Type: boolean Default: false

Java Code:

ConfigurationProperties.watchInitializationJson(boolean enable)

System Property:

-Dmockserver.watchInitializationJson=...

Environment Variable:

MOCKSERVER_WATCH_INITIALIZATION_JSON=...

Property File:

mockserver.watchInitializationJson=...

Example:

-Dmockserver.watchInitializationJson="org/mockserver/server/initialize/initializerJson.json"

Enable the persisting of expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)

Type: boolean Default: false

Java Code:

ConfigurationProperties.persistExpectations(boolean persistExpectations)

System Property:

-Dmockserver.persistExpectations=...

Environment Variable:

MOCKSERVER_PERSIST_EXPECTATIONS=...

Property File:

mockserver.persistExpectations=...

Example:

-Dmockserver.persistExpectations="true"

The file path used to save persisted expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)

Type: string Default: persistedExpectations.json

Java Code:

ConfigurationProperties.persistedExpectationsPath(String persistedExpectationsPath)

System Property:

-Dmockserver.persistedExpectationsPath=...

Environment Variable:

MOCKSERVER_PERSISTED_EXPECTATIONS_PATH=...

Property File:

mockserver.persistedExpectationsPath=...

Example:

-Dmockserver.persistedExpectationsPath="org/mockserver/server/initialize/initializerJson.json"