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

Note: all four 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();

When using Spring's @MockServerTest, the initializer class can be configured directly in the annotation:

@MockServerTest("mockserver.initializationClass=org.mockserver.server.initialize.ExpectationInitializerExample")
@RunWith(SpringRunner.class)
public class MyTest {
    private MockServerClient mockServerClient;  // auto-injected with expectations already loaded
}

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-6.1.0-no-dependencies.jar -serverPort 1080 -logLevel INFO

initializationJsonPath supports:

  • relative or absolute paths
  • both filesystem and classpath locations
  • multiple files by using glob patterns that can expand a wildcard pattern into a list of paths that match the given pattern using characters such as *, **, ?, [] and {}, for more details see glob patterns

Supported action types in JSON initializer files: httpResponse, httpResponseTemplate, httpForward, httpForwardTemplate, httpForwardClassCallback, httpResponseClassCallback, httpOverrideForwardedRequest, and httpError. WebSocket-based object callbacks (httpResponseObjectCallback and httpForwardObjectCallback) are not supported in JSON initialization files because they require an active WebSocket connection from a running client.

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"
    }
  }
]
 

JSON Schema for IDE Support

A self-contained JSON Schema is published for MockServer expectations, providing autocompletion and validation in IDEs such as VS Code, IntelliJ, and any editor that supports JSON Schema.

The schema is available at:

The schema is also registered with the JSON Schema Store, which means IDEs will automatically apply the schema to files matching these patterns:

  • mockserverInitialization.json — the default MockServer initialization file
  • *mockserver*Initialization.json — any initialization file containing "mockserver" and "Initialization" in the name
  • mockserver*.json — any JSON file starting with "mockserver"

To manually reference the schema in a JSON file, add a $schema property at the top level:

{
  "$schema": "https://www.mock-server.com/schema/expectations.json",
  ...
}
 

Multiple Files (Glob Patterns)

  • The * character matches zero or more characters of a name component without crossing directory boundaries.
  • The ** characters matches zero or more characters crossing directory boundaries.
  • The ? character matches exactly one character of a name component.
  • The backslash character (\) is used to escape characters that would otherwise be interpreted as special characters. The expression \\ matches a single backslash and "\{" matches a left brace for example.
  • The [ ] characters are a bracket expression that match a single character of a name component out of a set of characters. For example, [abc] matches "a", "b", or "c". The hyphen (-) may be used to specify a range so [a-z] specifies a range that matches from "a" to "z" (inclusive). These forms can be mixed so [abce-g] matches "a", "b", "c", "e", "f" or "g". If the character after the [ is a ! then it is used for negation so [!a-c] matches any character except "a", "b", or "c".
  • Within a bracket expression the *, ? and \ characters match themselves. The (-) character matches itself if it is the first character within the brackets, or the first character after the ! if negating.
  • The { } characters are a group of subpatterns, where the group matches if any subpattern in the group matches. The "," character is used to separate the subpatterns. Groups cannot be nested.
 

Expectation Initializer File Watcher

If a JSON expectation initializer or OpenAPI initializer is specified, a file watcher can be enabled that watches for changes in the initialization files and updates the expectations when a file is modified. Changes are detected at most after 5 seconds if the file contents has changed.

If enabled the initialization JSON and OpenAPI files will be watched for changes, any changes found will result in expectations being created, removed 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-6.1.0-no-dependencies.jar -serverPort 1080,1081 -logLevel INFO

or

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

Expectation Initializer OpenAPI

MockServer expectations can be initialized when the MockServer starts, using an OpenAPI v3 specification file (YAML or JSON), by specifying the initializationOpenAPIPath configuration property as described in the Configuration Properties page, for example:

java -Dmockserver.initializationOpenAPIPath="/config/petstore.yaml" -jar ~/Downloads/mockserver-netty-6.1.0-no-dependencies.jar -serverPort 1080 -logLevel INFO

MockServer will generate an expectation for each operation defined in the OpenAPI spec, with example responses derived from the schema definitions.

initializationOpenAPIPath supports:

  • relative or absolute paths
  • both filesystem and classpath locations
  • YAML (.yaml, .yml) and JSON (.json) OpenAPI v3 specifications
  • multiple files by using glob patterns (see glob patterns)

This can also be used with environment variables, which is particularly useful with Docker:

MOCKSERVER_INITIALIZATION_OPENAPI_PATH=/config/petstore.yaml \
java -jar ~/Downloads/mockserver-netty-6.1.0-no-dependencies.jar -serverPort 1080,1081 -logLevel INFO

Both initializationJsonPath and initializationOpenAPIPath can be used together. JSON expectations are loaded first, followed by OpenAPI expectations.

The file watcher (watchInitializationJson) also monitors OpenAPI files for changes when enabled.

 

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-6.1.0-no-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-6.1.0-no-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>6.1.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>

Note: the initializationJson parameter in the Maven plugin also supports glob patterns, allowing you to load expectations from multiple files using wildcards. For example:

<configuration>
    <serverPort>1080</serverPort>
    <initializationJson>src/test/resources/expectations/**/*.json</initializationJson>
</configuration>

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 PluginExpectationInitializer {

    @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=...

Spring @MockServerTest:

@MockServerTest("mockserver.initializationClass=org.mockserver.server.initialize.ExpectationInitializerExample")

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"

The path to the OpenAPI spec file used to initialize expectations in MockServer at startup, if set MockServer will load this file and create expectations for each operation when it starts.

The file can be a YAML (.yaml, .yml) or JSON (.json) OpenAPI v3 specification. MockServer will generate an expectation for each operation defined in the spec, with example responses derived from the schema.

To watch multiple files use file globs as documented here: glob patterns

Type: string Default: null

Java Code:

ConfigurationProperties.initializationOpenAPIPath(String initializationOpenAPIPath)

System Property:

-Dmockserver.initializationOpenAPIPath=...

Environment Variable:

MOCKSERVER_INITIALIZATION_OPENAPI_PATH=...

Property File:

mockserver.initializationOpenAPIPath=...

Example:

-Dmockserver.initializationOpenAPIPath="/config/petstore.yaml"

If enabled the initialization JSON file and OpenAPI file will be watched for changes, any changes found will result in expectations being created, removed 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="false"

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"

Enable the persisting of recorded expectations (proxy traffic) as json, which is updated whenever a new request is forwarded through the proxy.

The persisted file can be loaded on restart using initializationJsonPath to replay recorded traffic as mock expectations.

Type: boolean Default: false

Java Code:

ConfigurationProperties.persistRecordedExpectations(boolean enable)

System Property:

-Dmockserver.persistRecordedExpectations=...

Environment Variable:

MOCKSERVER_PERSIST_RECORDED_EXPECTATIONS=...

Property File:

mockserver.persistRecordedExpectations=...

Example:

-Dmockserver.persistRecordedExpectations="true"

The file path used to save persisted recorded expectations as json, which is updated whenever a new request is forwarded through the proxy.

Type: string Default: persistedRecordedExpectations.json

Java Code:

ConfigurationProperties.persistedRecordedExpectationsPath(String persistedRecordedExpectationsPath)

System Property:

-Dmockserver.persistedRecordedExpectationsPath=...

Environment Variable:

MOCKSERVER_PERSISTED_RECORDED_EXPECTATIONS_PATH=...

Property File:

mockserver.persistedRecordedExpectationsPath=...

Example:

-Dmockserver.persistedRecordedExpectationsPath="recordedExpectations.json"
 

Verification Configuration:

The maximum number of requests to return in verification failure result, if more expectations are found the failure result does not list them separately

Type: int Default: 10

Java Code:

ConfigurationProperties.maximumNumberOfRequestToReturnInVerificationFailure(Integer maximumNumberOfRequestToReturnInVerificationFailure)

System Property:

-Dmockserver.maximumNumberOfRequestToReturnInVerificationFailure=...

Environment Variable:

MOCKSERVER_MAXIMUM_NUMBER_OF_REQUESTS_TO_RETURN_IN_VERIFICATION_FAILURE=...

Property File:

mockserver.maximumNumberOfRequestToReturnInVerificationFailure=...

Example:

-Dmockserver.maximumNumberOfRequestToReturnInVerificationFailure="20"