--- title: Expectation Initializers description: Load expectations automatically when MockServer starts using a Java initializer class, JSON file, OpenAPI spec, or Maven plugin initializer. layout: page pageOrder: 6 section: 'Mock Server' subsection: true sitemap: priority: 0.7 changefreq: 'monthly' lastmod: 2019-11-10T08:00:00+01:00 ---

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-{{ site.mockserver_version }}-no-dependencies.jar -serverPort 1080 -logLevel INFO

initializationJsonPath supports:

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:

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)

 

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-{{ site.mockserver_version }}-no-dependencies.jar -serverPort 1080,1081 -logLevel INFO

or

java \
-Dmockserver.watchInitializationJson=true \
-Dmockserver.initializationJsonPath=mockserverInitialization.json \
-jar ~/Downloads/mockserver-netty-{{ site.mockserver_version }}-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-{{ site.mockserver_version }}-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:

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-{{ site.mockserver_version }}-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.

{% include_subpage _includes/clustering.html %}  

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

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")
                );
    }
}
{% include_subpage _includes/initializer_persistence_configuration.html %}