Expectation Initializers
To ensure expectations are available as soon as MockServer is started it is possible to use an expectation initializer, there are three options:
- initializer class loaded from the classpath to construct an array of expectations
- initializer JSON file loaded from the filesystem containing a serialised array of expectations
- maven plugin initializer class loaded from the classpath to add expectations using the MockServerClient
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.13.2-shaded.jar -serverPort 1080 -logLevel INFO
initializationJsonPath supports:
- related 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
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"
}
}
]
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 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. Changes are detected at most after 5 seconds if the file contents has changed.
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 first duplicate key in the file will be processed and all duplicates except the first duplicate will be ignored.
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.13.2-shaded.jar -serverPort 1080,1081 -logLevel INFO
or
java \
-Dmockserver.watchInitializationJson=true \
-Dmockserver.initializationJsonPath=mockserverInitialization.json \
-jar ~/Downloads/mockserver-netty-5.13.2-shaded.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:
- share a read-write file system i.e. same physical / virtual machine, NFS, AWS EFS, Azure Files, etc
- configure identical expectation initialiser and expectation persistence
- bind to a free port i.e. separate ports if on same physical / virtual machine
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.13.2-shaded.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.13.2-shaded.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.13.2</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="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"
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(String maximumNumberOfRequestToReturnInVerificationFailure)
System Property:
-Dmockserver.maximumNumberOfRequestToReturnInVerificationFailure=...
Environment Variable:
MOCKSERVER_MAXIMUM_NUMBER_OF_REQUESTS_TO_RETURN_IN_VERIFICATION_FAILURE=...
Property File:
mockserver.maximumNumberOfRequestToReturnInVerificationFailure=...
Example:
-Dmockserver.maximumNumberOfRequestToReturnInVerificationFailure="org/mockserver/server/initialize/initializerJson.json"