MockServer has the following clients:

All clients support:

  • creating expectations with mock responses
  • creating expectations which forward
  • creating expectations which use a callback
  • verifying which requests have been received
  • clearing expectations (selectively)
  • resetting (clearing all expectations)
  • dumping all expectations to the log (for debugging)

Note: It is not necessary to use the provided clients because the MockServer web api is designed to be very simple JSON/HTTP so it is easy to interact directly with the MockServer with any HTTP client.

 

MockServer Java Client

This section includes an overview with a few basic examples then a detailed description of the Java client API.

Java Client Examples

To setup an expectation that responds to a request:

new MockServerClient("127.0.0.1", 1080)
        .when(
                request()
                        .withMethod("POST")
                        .withPath("/login")
                        .withQueryStringParameters(
                                new Parameter("returnUrl", "/account")
                        )
                        .withCookies(
                                new Cookie("sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW")
                        )
                        .withBody(exact("{username: 'foo', password: 'bar'}")),
                exactly(1)
        )
        .respond(
                response()
                        .withStatusCode(401)
                        .withHeaders(
                                new Header("Content-Type", "application/json; charset=utf-8"),
                                new Header("Cache-Control", "public, max-age=86400")
                        )
                        .withBody("{ message: 'incorrect username and password combination' }")
                        .withDelay(new Delay(SECONDS, 1))
        );

To setup an expectation that forwards to a request:

new MockServerClient("127.0.0.1", 1080)
        .when(
                request()
                        .withMethod("GET")
                        .withPath("/index.html"),
                exactly(1)
        )
        .forward(
                forward()
                        .withHost("www.mock-server.com")
                        .withPort(80)
                        .withScheme(HTTP)
        );

To start a local instance of MockServer and setup an expectation that executes a callback:

MockServerClient mockServer = startClientAndServer(1080);

mockServer
        .when(
                request()
                        .withPath("/callback")
        )
        .callback(
                callback()
                        .withCallbackClass("org.mockserver.server.PrecannedTestExpectationCallback")
        );

and the callback class could be as follows:

public class PrecannedTestExpectationCallback implements ExpectationCallback {

    public static HttpResponse httpResponse = response()
            .withStatusCode(ACCEPTED_202.code())
            .withHeaders(
                    header("x-callback", "test_callback_header"),
                    header("Content-Length", "a_callback_response".getBytes().length),
                    header("Connection", "keep-alive")
            )
            .withBody("a_callback_response");

    @Override
    public HttpResponse handle(HttpRequest httpRequest) {
        if (httpRequest.getPath().getValue().endsWith("/callback")) {
            return httpResponse;
        } else {
            return notFoundResponse();
        }
    }
}

Note: these examples require the use of these static imports as follows:

import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.matchers.Times.exactly; import static java.util.concurrent.TimeUnit.SECONDS; import static org.mockserver.model.HttpForward.Scheme.HTTP; import static org.mockserver.model.HttpStatusCode.ACCEPTED_202;

The mockserver-example project contains multiple examples such as BookPageIntegrationTest that demonstrates a fully working examples.

Java Client API

The client API consists of two main classes:

  • org.mockserver.client.server.MockServerClient - makes HTTP requests to a remote MockServer instance
  • org.mockserver.integration.ClientAndServer - starts a MockServer instance and makes HTTP requests to it

Both classes expose the same API as follows:

public class MockServerClient {

    /**
     * Start the client communicating to a MockServer at the specified host and port
     * for example:
     *
     *   MockServerClient mockServerClient = new MockServerClient("localhost", 1080);
     *
     * @param host the host for MockServer to communicate with
     * @param port the port for MockServer to communicate with
     */
    public MockServerClient(String host, int port);

    /**
     * Start the client communicating to a MockServer at the specified host and port
     * and contextPath for example:
     *
     *   MockServerClient mockServerClient = new MockServerClient("localhost", 1080);
     *
     * @param host the host for MockServer to communicate with
     * @param port the port for MockServer to communicate with
     * @param contextPath the context path that MockServer war is deployed to
     */
    public MockServerClient(String host, int port, String contextPath);

    /**
     * Specify an unlimited expectation that will respond regardless of the number of matching http
     * for example:
     *
     *   mockServerClient
     *           .when(
     *                   request()
     *                           .withPath("/some_path")
     *                           .withBody("some_request_body")
     *           )
     *           .respond(
     *                   response()
     *                           .withBody("some_response_body")
     *                           .withHeaders(
     *                                   new Header("responseName", "responseValue")
     *                           )
     *           );
     *
     * @param httpRequest the http request that must be matched for this expectation to respond
     * @return an Expectation object that can be used to specify the response
     */
    public ForwardChainExpectation when(HttpRequest httpRequest);

    /**
     * Specify an limited expectation that will respond a specified number of times when the http is matched
     * for example:
     *
     *   mockServerClient
     *           .when(
     *                   new HttpRequest()
     *                           .withPath("/some_path")
     *                           .withBody("some_request_body"),
     *                   Times.exactly(5)
     *           )
     *           .respond(
     *                   new HttpResponse()
     *                           .withBody("some_response_body")
     *                           .withHeaders(
     *                                   new Header("responseName", "responseValue")
     *                           )
     *           );
     *
     * @param httpRequest the http request that must be matched for this expectation to respond
     * @param times       the number of times to respond when this http is matched
     * @return an Expectation object that can be used to specify the response
     */
    public ForwardChainExpectation when(HttpRequest httpRequest, Times times);

    /**
     * Specify an limited expectation that will respond a specified number of times when the http is matched
     * for example:
     *
     *   mockServerClient
     *           .when(
     *                   new HttpRequest()
     *                           .withPath("/some_path")
     *                           .withBody("some_request_body"),
     *                   Times.exactly(5)
     *           )
     *           .respond(
     *                   new HttpResponse()
     *                           .withBody("some_response_body")
     *                           .withHeaders(
     *                                   new Header("responseName", "responseValue")
     *                           )
     *           );
     *
     * @param httpRequest the http request that must be matched for this expectation to respond
     * @param times       the number of times to respond when this http is matched
     * @param timeToLive  the length of time from when the server receives the expectation that the expectation should be active
     * @return an Expectation object that can be used to specify the response
     */
    public ForwardChainExpectation when(HttpRequest httpRequest, Times times, TimeToLive timeToLive);

    /**
     * Reset MockServer by clearing all expectations
     */
    public MockServerClient reset();

    /**
     * Stop MockServer gracefully (only support for Netty and Vert.X versions, not supported for WAR version)
     */
    public MockServerClient stop();

    /**
     * Clear all expectations that match the http
     *
     * @param httpRequest the http request that is matched against when deciding whether to clear each expectation if null all expectations are cleared
     */
    public MockServerClient clear(HttpRequest httpRequest);

    /**
     * Verify a request has been sent for example:
     *
     *   mockServerClient
     *           .verify(
     *                   request()
     *                           .withPath("/some_path")
     *                           .withBody("some_request_body")
     *           );
     *
     * @param httpRequests the http requests that must be matched for this verification to pass
     * @throws AssertionError if the request has not been found
     */
    public MockServerClient verify(HttpRequest... httpRequests); throws AssertionError

    /**
     * Verify a request has been sent for example:
     *
     *   mockServerClient
     *           .verify(
     *                   request()
     *                           .withPath("/some_path")
     *                           .withBody("some_request_body"),
     *                   VerificationTimes.exactly(3)
     *           );
     *
     * Times supports multiple static factory methods:
     *
     *   once()      - verify the request was only received once
     *   exactly(n)  - verify the request was only received exactly n times
     *   atLeast(n)  - verify the request was only received at least n times
     *
     * @param httpRequest the http request that must be matched for this verification to pass
     * @param times       the number of times this request must be matched
     * @throws AssertionError if the request has not been found
     */
    public MockServerClient verify(HttpRequest httpRequest, org.mockserver.verify.VerificationTimes times); throws AssertionError

    /**
     * Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requests
     *
     * @param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests
     * @return an array of all expectations that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
     */
    public HttpRequest[] retrieveRecordedRequests(HttpRequest httpRequest);

    /**
     * Retrieve the already setup expectations match the httpRequest parameter, use null for the parameter to retrieve all expectations
     *
     * @param httpRequest the http request that is matched against when deciding whether to return each expectation, use null for the parameter to retrieve for all requests
     * @return an array of all expectations that have been setup
     */
    public Expectation[] retrieveExistingExpectations(HttpRequest httpRequest);
}
 

MockServer JavaScript Client

This section includes an overview with a few basic examples then a detailed description of the JavaScript client API.

To interact with MockServer from JavaScript it is possible to use either:

To include the browser based in an HTML page use one of the following script tag to load the file from MaxCDN:

<script type="text/javascript" src="https://cdn.rawgit.com/jamesdbloom/mockserver/6a2fb42cb7933d0d68e7d595785a9b0536450825/mockserver-client-javascript/src/main/javascript/mockServerClient.js"></script>

To use the Node.js module add the following code to your node project:

var mockServer = require('mockserver-client'),
    mockServerClient = mockServer.mockServerClient;

JavaScript Client Examples

To setup a simple expectation that returns a JSON body for all requests on a given path:

mockServerClient("localhost", 1080).mockSimpleResponse('/somePath', { name: 'value' }, 203);

To setup a more complex expectation:

mockServerClient("localhost", 1080).mockAnyResponse(
    {
        'httpRequest': {
            'method': 'POST',
            'path': '/somePath',
            'queryStringParameters': [
                {
                    'name': 'test',
                    'values': [ 'true' ]
                }
            ],
            'body': {
                'type': 'STRING',
                'value': 'someBody'
            }
        },
        'httpResponse': {
            'statusCode': 200,
            'body': JSON.stringify({ name: 'value' }),
            'delay': {
                'timeUnit': 'MILLISECONDS',
                'value': 250
            }
        },
        'times': {
            'remainingTimes': 1,
            'unlimited': false
        }
    }
);

To setup an expectation that forwards all requests:

mockServerClient("localhost", 1080).mockAnyResponse(
    {
        'httpRequest': {
            'method': 'GET',
            'path': '/somePath'
        },
        "httpForward": {
            "host": "www.mock-server.com",
            "port": 80,
            "scheme": "HTTP"
        },
        'times': {
            'remainingTimes': 1,
            'unlimited': false
        }
    }
);

It is also possible to make AJAX calls directly without the client as follows:

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("PUT", "http://localhost:1080/expectation", false);
xmlHttpRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlHttpRequest.send(JSON.stringify({
    "httpRequest": {
        "method": "POST",
        "path": "/login",
        "body": {
            "type": "JSON",
            "value": JSON.stringify({ username: "foo", password: "bar" })
        }
    },
    "httpResponse": {
        "statusCode": 401,
        "headers": [
            {
                "name": "Content-Type",
                "values": ["application/json; charset=utf-8"]
            },
            {
                "name": "Cache-Control",
                "values": ["public, max-age=86400"]
            }
        ],
        "body": JSON.stringify({ message: "incorrect username and password combination" })
    }
}));

JavaScript Client API

Both versions of mockServerClient provide the same API as follows:

var mockServerClient = function (mockServerUrl) {
    "use strict";

    /**
     * The default headers added to to the mocked response when using mockSimpleResponse(...)
     */
    var defaultResponseHeaders = [
            {'name': 'Content-Type', 'values': ['application/json; charset=utf-8']},
            {'name': 'Cache-Control', 'values': ['no-cache, no-store']}
    ],

    /**
     * Setup an expectation in MockServer by specifying an expectation object
     * for example:
     *
     *   mockServerClient('localhost', 1080).mockAnyResponse(
     *       {
     *           'httpRequest': {
     *               'path': '/somePath',
     *               'body': {
     *                   'type': 'STRING',
     *                   'value': 'someBody'
     *               }
     *           },
     *           'httpResponse': {
     *               'statusCode': 200,
     *               'body': Base64.encode(JSON.stringify({ name: 'first_body' })),
     *               'delay': {
     *                   'timeUnit': 'MILLISECONDS',
     *                   'value': 250
     *               }
     *           },
     *           'times': {
     *               'remainingTimes': 1,
     *               'unlimited': false
     *           }
     *       }
     *   );
     *
     * @param expectation the expectation to setup in MockServer
     */
    mockAnyResponse = function (expectation),

    /**
     * Setup an expectation in MockServer without having to specify the full expectation object
     * for example:
     *
     *   mockServerClient('localhost', 1080).mockSimpleResponse('/somePath', { 'name': 'value' }, 203);
     *
     * @param path         the path to match requests against
     * @param responseBody the response body to return if a request matches
     * @param statusCode   the response code to return if a request matches
     */
    mockSimpleResponse = function (path, responseBody, statusCode),

    /**
     * Override the default headers that are used to specify the response headers in mockSimpleResponse(...)
     * (note: if you use mockAnyResponse(...) the default headers are not used)
     * for example:
     *
     *   mockServerClient('localhost', 1080).setDefaultHeaders([
     *       {'name': 'Content-Type', 'values': ['application/json; charset=utf-8']},
     *       {'name': 'Cache-Control', 'values': ['no-cache, no-store']}
     *   ])
     *
     * @param headers the path to match requests against
     */
    setDefaultHeaders = function (headers),

    /**
     * Verify a request has been sent for example:
     *
     *   client.verify({
     *       'httpRequest': {
     *           'method': 'POST',
     *           'path': '/somePath'
     *       }
     *   }, 2, true);
     *
     * @param request the http request that must be matched for this verification to pass
     * @param count   the number of times this request must be matched
     * @param exact   true if the count is matched as "equal to" or false if the count is matched as "greater than or equal to"
     * @throws an error is the verify fails detailing which requests have been sent
     */
    verify = function (request, count, exact),

    /**
     * Verify a sequence of requests has been sent for example:
     *
     *   client.verifySequence(
     *       {
     *          'method': 'POST',
     *          'path': '/first_request'
     *       },
     *       {
     *          'method': 'POST',
     *          'path': '/second_request'
     *       },
     *       {
     *          'method': 'POST',
     *          'path': '/third_request'
     *       }
     *   );
     *
     * @param arguments the list of http requests that must be matched for this verification to pass
     * @throws an error is the verify fails detailing which requests have been sent
     */
    verifySequence = function (),

    /**
     * Reset MockServer by clearing all expectations
     */
    reset = function (path),

    /**
     * Clear all expectations that match the specified path
     *
     * @param path the path to decide which expectations to cleared
     */
    clear = function (path),

    /**
     * Retrieve the recorded requests that match the parameter, as follows:
     * - use a string value to match on path,
     * - use a request matcher object to match on a full request,
     * - or use null to retrieve all requests
     *
     * @param pathOrRequestMatcher  if a string is passed in the value will be treated as the path, however
     *                              if an object is passed in the value will be treated as a full request
     *                              matcher object, if null is passed in it will be treated as match all
     */
    retrieveRequests = function (pathOrRequestMatcher),

    /**
     * Retrieve the setup expectations that match the parameter,
     * the expectation is retrieved by matching the parameter
     * on the expectations own request matcher, as follows:
     * - use a string value to match on path,
     * - use a request matcher object to match on a full request,
     * - or use null to retrieve all requests
     *
     * @param pathOrRequestMatcher  if a string is passed in the value will be treated as the path, however
     *                              if an object is passed in the value will be treated as a full request
     *                              matcher object, if null is passed in it will be treated as match all
     */
    retrieveExpectations = function (pathOrRequestMatcher);

    return {
        mockAnyResponse: mockAnyResponse,
        mockSimpleResponse: mockSimpleResponse,
        setDefaultHeaders: setDefaultHeaders,
        verify: verify,
        reset: reset,
        clear: clear,
        retrieveRequests: retrieveRequests,
        retrieveExpectations: retrieveExpectations
    };
};
 

MockServer Ruby Client  Gem Version

This section includes an overview with a few basic examples then a detailed description of the Java client API.

To interact with MockServer from Ruby use mockserver-client gem as follows:

Add the gem to the application Gemfile:

gem 'mockserver-client'

Or install the gem directly:

gem install mockserver-client

Ruby Client Examples

To setup an expectation that responds to a request:

require "mockserver-client"

class SomeClass

  include MockServer
  include MockServer::Model::DSL

  def createExpectation
    client = MockServerClient.new('localhost', 1080)
    expectation = expectation do |expectation|
         expectation.request do |request|
            request.method = 'POST'
            request.path = '/login'
            request.query_string_parameters << parameter('returnUrl', '/account')
            request.cookies = [cookie('sessionId', '2By8LOhBmaW5nZXJwcmludCIlMDAzMW')]
            request.body = exact({ username: 'foo', password: 'bar' }.to_json)
         end

        expectation.response do |response|
            response.status_code = 401
            response.headers << header('Content-Type', 'application/json; charset=utf-8')
            response.headers << header('Cache-Control', 'public, max-age=86400')
            response.body  = body({ message: 'incorrect username and password combination' }.to_json)
            response.delay = delay_by(:SECONDS, 1)
        end
    end
    client.register(expectation)
  end

end

To setup an expectation that forwards all requests:

client = MockServerClient.new('localhost', 1080)
expectation = expectation do |expectation|
     expectation.request do |request|
        request.method = 'GET'
        request.path = '/somePath'
     end

    expectation.forward do |forward|
        forward.host = 'www.mock-server.com'
        forward.port = 80
        forward.scheme = :HTTP
    end

    expectation.times = exactly(2)
end
client.register(expectation)