Note: this page is a high level overview of each topic, more detail is available for each topic on a linked page.

To use MockServer Proxy to analysis an existing system:

  1. Start MockServer Proxy
  2. Configure Clients
  3. Run Scenarios
  4. Analyse Behaviour

Mocking service dependencies with MockServer

To use MockServer Proxy to verify requests:

  1. Start MockServer Proxy
  2. Configure Clients
  3. Run Test Scenarios
  4. Verify Requests

Mocking service dependencies with MockServer

0. Start MockServer

MockServer is flexible and support numerous usage patterns.

The MockServer and MockServer Proxy can be run:

MockServer and MockServer Proxy is available as:

It is also possible to build and run MockServer directly from source code

To simplify configuration all MockServer versions (except the deployable WAR) only use a single port to support HTTP, HTTPS and SOCKS. This is achieved by dynamically detecting if the client is using HTTP, HTTPS or SOCKS.

Start MockServer Proxy

If the proxy is being started programmatically from within the same JVM using org.mockserver.proxy.ProxyRunner or org.mockserver.integration.ClientAndProxy then the environment variables "http.proxyHost" and "http.proxyPort" will be set automatically.

If the proxy is being started as separate JVM, for example using the command line, then the system being analysed needs the following command line options to set the correct environment variables.

-Dhttp.proxyHost=<proxy hostname> -Dhttp.proxyPort=<proxy port>

For example:

-DproxySet=true -Dhttp.proxyHost=localhost -Dhttp.proxyPort=1090

Configuring Clients

The system that is being analysed must be configured to use the proxy.

Viewing Recorded Request & Responses

 

3. Analysing Behaviour

To analyse the requests that a system makes the proxy can be used to record all requests and write them into the mockserver_request.log. This can be particularly helpful when refactoring an existing or legacy system.

The requests can be written to the log in JSON or as Java code. The Java code can then be used to setup expectations in MockServer and exactly replay all interactions.

The request and responses recorded by the MockServer Proxy can be written to the request log as Java code, as follows:

new ProxyClient("localhost", 1090)
        .dumpToLogAsJava(
                request()
                        .withMethod("POST")
                        .withPath("/login")
        );

The Java code format that requests are written to the logs is as follows:

new MockServerClient()
        .when(
                request()
                        .withMethod("GET")
                        .withPath("/get_book")
                        .withQueryString("id=1")
                        .withHeaders(
                                new Header("Accept-Encoding", "gzip"),
                                new Header("Host", "localhost:1090"),
                                new Header("User-Agent", "Jetty/8.1.13.v20130916")
                        ),
                Times.once()
        )
        .respond(
                response()
                        .withStatusCode(200)
                        .withHeaders(
                                new Header("Server", "Jetty(8.1.13.v20130916)")
                        )
                        .withBody("{\n        \"id\": \"1\",\n        \"title\": \"Xenophon's imperial fiction : on the education of Cyrus\",\n        \"author\": \"James Tatum\",\n        \"isbn\": \"0691067570\",\n        \"publicationDate\": \"1989\"\n    }")
        );

The request and responses recorded by the MockServer Proxy can be written to the request log as JSON, as follows:

new ProxyClient("localhost", 1090)
        .dumpToLogAsJSON(
                request()
                        .withMethod("POST")
                        .withPath("/login")
        );

This would result in entries in the mockserver_request.log file of the following format:

{
    "httpRequest": {
        "method": "POST",
        "path": "/login",
        "body": {
            "type": "STRING",
            "value": "{username: 'foo', password: 'bar'}",
        },
        "cookies": [
            {
                "name": "sid",
                "values": [ "05F1A3D2F2143C49727" ]
            }
        ],
        "headers": [
            {
                "name": "Accept-Language",
                "values": [ "en-US,en;q=0.8,fa;q=0.6" ]
            },
            {
                "name": "Cookie",
                "values": [ "sid=05F1A3D2F2143C49727" ]
            },
            {
                "name": "Host",
                "values": [ "localhost:2021" ]
            },
            {
                "name": "Content-Length",
                "values": [ "34" ]
            },
            {
                "name": "Accept-Encoding",
                "values": [ "gzip,deflate,sdch" ]
            },
            {
                "name": "User-Agent",
                "values": [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36" ]
            },
            {
                "name": "Accept",
                "values": [ "*/*" ]
            },
            {
                "name": "Content-Type",
                "values": [ "text/plain" ]
            }
        ]
    },
    "httpResponse": {
        "statusCode": 200,
        "body": "{ message: 'success' }",
        "headers": [
            {
                "name": "Content-Type",
                "values": [ "application/json; charset=utf-8" ]
            },
            {
                "name": "Cache-Control",
                "values": [ "no-cache, no-store" ]
            }
        ]
    },
    "times": {
        "remainingTimes": 1,
        "unlimited": false
    }
}

3. Verify Requests

The MockServer Proxy allows the verification of requests by specifying:

  • an amount of a single type of request
  • a sequence of requests that is verified in order

Verifying Repeating Requests

To verify that a request has been sent use the verify method of the ProxyClient as follows:

new ProxyClient("localhost", 1090).verify(
        request()
                .withMethod("POST")
                .withPath("/login")
                .withBody(exact("{username: 'foo', password: 'bar'}"))
                .withCookies(
                        new Cookie("sessionId", ".*")
                ),
        VerificationTimes.exactly(1)
);

The org.mockserver.verify.VerificationTimes class is used to specify how many times you want MockServer to match a request:

To create an instance of VerificationTimes use one of the static factory methods:

VerificationTimes.once();
VerificationTimes.exactly(int count);
VerificationTimes.atLeast(int count);

Verifying Request Sequences

To verify that the system under test has sent a sequence of requests to MockServer use the verify method of the MockServerClient as follows:

new ProxyClient("localhost", 1090).verify(
        request()
                .withMethod("POST")
                .withPath("/login")
                .withBody(exact("{username: 'foo', password: 'bar'}"))
                .withCookies(
                        new Cookie("sessionId", ".*")
                ),
        request()
                .withMethod("POST")
                .withPath("/deposit")
                .withBody(exact("{acccount: '123456789', card: '1234 5678 9012 3456', amount: '10.00'}"))
                .withCookies(
                        new Cookie("sessionId", ".*")
                ),
        request()
                .withMethod("POST")
                .withPath("/logout")
                .withCookies(
                        new Cookie("sessionId", ".*")
                )
);

The each request in the sequence will be verified to have been received at least once, in the exact order specified.

The mockserver-example project contains an example test called BookPageIntegrationTest that demonstrates a fully working example.