When a request matches an expectation , MockServer executes the expectation’s action . There are four action types:
Response Return a fixed or templated HTTP response.
Forward Proxy the request to another server, optionally modifying it.
Callback Invoke a Java class or closure to generate the response dynamically.
Error Return invalid bytes or drop the connection to simulate network failures.
Response
A response action returns an HTTP response you define. You can set the status code, reason phrase, headers, cookies, body, and delay.
Status code and reason phrase
new MockServerClient ( "localhost" , 1080 )
. when (
request ()
. withMethod ( "POST" )
. withPath ( "/some/path" )
)
. respond (
response ()
. withStatusCode ( 418 )
. withReasonPhrase ( "I'm a teapot" )
);
Headers, cookies, and body
new MockServerClient ( "localhost" , 1080 )
. when ( request ())
. respond (
response ()
. withBody ( "some_response_body" )
. withHeader ( "Content-Type" , "plain/text" )
. withCookie ( "Session" , "97d43b1e-fe03-4855-926a-f448eddac32f" )
);
Delay
new MockServerClient ( "localhost" , 1080 )
. when (
request (). withPath ( "/some/path" )
)
. respond (
response ()
. withBody ( "some_response_body" )
. withDelay ( TimeUnit . SECONDS , 10 )
);
Connection options
Use connectionOptions to suppress or override automatically-added headers, or to close the socket:
response ()
. withBody ( "some_response_body" )
. withConnectionOptions (
connectionOptions ()
. withSuppressConnectionHeader ( true )
. withSuppressContentLengthHeader ( true )
)
Close the connection after sending the response:
"connectionOptions" : { "closeSocket" : true }
Close the connection after a delay:
"connectionOptions" : {
"closeSocket" : true ,
"closeSocketDelay" : { "timeUnit" : "MILLISECONDS" , "value" : 500 }
}
Respond differently for the same request
Register multiple expectations with the same matcher and different times values. MockServer fires them in registration order:
# respond once with 200, then twice with 204
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": { "path": "/some/path" },
"httpResponse": { "statusCode": 200 },
"times": { "remainingTimes": 1, "unlimited": false }
}'
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": { "path": "/some/path" },
"httpResponse": { "statusCode": 204 },
"times": { "remainingTimes": 2, "unlimited": false }
}'
Response templates
You can use Mustache, Velocity, or JavaScript templates to generate responses dynamically from the incoming request. See Response Templates .
Java (JavaScript template)
REST API (JavaScript template)
new MockServerClient ( "localhost" , 1080 )
. when ( request (). withPath ( "/some/path" ))
. respond (
template (
HttpTemplate . TemplateType . JAVASCRIPT ,
"return { \n " +
" 'statusCode': 200, \n " +
" 'cookies': { 'session': request.headers['Session-Id'][0] }, \n " +
" 'headers': { 'Date': [ Date() ] }, \n " +
" 'body': JSON.stringify({ method: request.method, path: request.path }) \n " +
"};"
)
);
Forward
A forward action proxies the incoming request to another server.
Forward exact request
new MockServerClient ( "localhost" , 1080 )
. when (
request (). withPath ( "/some/path" )
)
. forward (
forward ()
. withHost ( "mock-server.com" )
. withPort ( 80 )
);
Use "scheme": "HTTPS" to forward over TLS:
"httpForward" : {
"host" : "mock-server.com" ,
"port" : 443 ,
"scheme" : "HTTPS"
}
Override the forwarded request
Replace specific fields of the request before forwarding:
new MockServerClient ( "localhost" , 1080 )
. when (
request (). withPath ( "/some/path" )
)
. forward (
forwardOverriddenRequest (
request ()
. withPath ( "/some/other/path" )
. withHeader ( "Host" , "target.host.com" )
)
);
Override both request and response
You can override the forwarded request and also replace the response body returned to the caller:
"httpOverrideForwardedRequest" : {
"httpRequest" : {
"path" : "/some/other/path" ,
"headers" : { "Host" : [ "target.host.com" ] }
},
"httpResponse" : {
"body" : "some_overridden_body"
}
}
Add delay to a forward
"httpOverrideForwardedRequest" : {
"httpRequest" : { "path" : "/some/other/path" },
"delay" : { "timeUnit" : "SECONDS" , "value" : 10 }
}
Callback
A callback action dynamically generates the response (or the forwarded request) by invoking code you provide. There are two variants: a class callback (server-side, Java only) and a method/closure callback (client-side, via WebSocket).
Class callback
Implement ExpectationResponseCallback and register it by class name. The class must be on MockServer’s classpath and have a zero-argument constructor.
public class TestExpectationResponseCallback implements ExpectationResponseCallback {
@ Override
public HttpResponse handle ( HttpRequest httpRequest ) {
if ( httpRequest . getPath (). getValue (). endsWith ( "/path" )) {
return response ()
. withStatusCode ( 202 )
. withBody ( "a_callback_response" );
} else {
return notFoundResponse ();
}
}
}
new ClientAndServer ( 1080 )
. when (
request (). withPath ( "/some.*" )
)
. respond (
callback ()
. withCallbackClass ( TestExpectationResponseCallback . class )
);
When using the Maven plugin with forked goals, add callback classes as plugin dependencies so MockServer can load them from the classpath.
Error
An error action simulates network-level failures by sending invalid bytes or dropping the TCP connection.
Drop the connection
new MockServerClient ( "localhost" , 1080 )
. when (
request (). withPath ( "/some/path" )
)
. error (
error ()
. withDropConnection ( true )
);
Send random bytes then drop
byte [] randomByteArray = new byte [ 25 ];
new Random (). nextBytes (randomByteArray);
new MockServerClient ( "localhost" , 1080 )
. when (
request (). withPath ( "/some/path" )
)
. error (
error ()
. withDropConnection ( true )
. withResponseBytes (randomByteArray)
);
responseBytes is a base64-encoded byte array.