MockServer supports the following features to simplify debugging

The simplest way to debug MockServer is to use the UI to view logs, requests and expectations

 

Retrieving Active Expectations

It is possible to retrieve the active expectations, as show below in the code examples.

Expectations are returned in the order they have been added. The expectations are returned can be filter using a request matcher.

Expectation[] activeExpectations = new MockServerClient("localhost", 1080)
    .retrieveActiveExpectations(
        request()
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
    .retrieveActiveExpectations({})
    .then(
        function (activeExpectations) {
            console.log(JSON.stringify(activeExpectations));
        },
        function (error) {
            console.log(error);
        }
    );

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS"

See REST API for full JSON specification

Expectation[] activeExpectations = new MockServerClient("localhost", 1080)
    .retrieveActiveExpectations(
        request()
            .withPath("/some/path")
            .withMethod("POST")
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveActiveExpectations({
    "path": "/some/path",
    "method": "POST"
}).then(
    function (activeExpectations) {
        console.log(JSON.stringify(activeExpectations));
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS" -d '{
    "path": "/some/path",
    "method": "POST"
}'

See REST API for full JSON specification

String activeExpectations = new MockServerClient("localhost", 1080)
    .retrieveActiveExpectations(
        request()
            .withPath("/some/path")
            .withMethod("POST"),
        Format.JAVA
    );
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS&format=JAVA" -d '{
    "path": "/some/path"
}'

See REST API for full JSON specification

String activeExpectations = new MockServerClient("localhost", 1080)
    .retrieveActiveExpectations(
        request()
            .withPath("/some/path")
            .withMethod("POST"),
        Format.JSON
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveActiveExpectations({
    "path": "/some/path",
    "method": "POST"
}).then(
    function (activeExpectations) {
        console.log(JSON.stringify(activeExpectations));
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS&format=JSON" -d '{
    "path": "/some/path"
}'

See REST API for full JSON specification

 

Retrieving Recorded Expectations

All proxied requests including those proxied using a forward actions are recorded containing the request received and response returned.

It is possible to retrieve the recorded requests and responses as expectations so that they can be easily used as expectations to simulation a system.

Expectations are returned in the order they have been recorded. The expectations are returned can be filter using a request matcher.

Expectation[] recordedExpectations = new MockServerClient("localhost", 1080)
    .retrieveRecordedExpectations(
        request()
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
    .retrieveRecordedExpectations({})
    .then(
        function (recordedExpectations) {
            console.log(JSON.stringify(recordedExpectations));
        },
        function (error) {
            console.log(error);
        }
    );

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS"

See REST API for full JSON specification

Expectation[] recordedExpectations = new MockServerClient("localhost", 1080)
    .retrieveRecordedExpectations(
        request()
            .withPath("/some/path")
            .withMethod("POST")
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedExpectations({
    "path": "/some/path",
    "method": "POST"
}).then(
    function (recordedExpectations) {
        console.log(JSON.stringify(recordedExpectations));
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS" -d '{
    "path": "/some/path",
    "method": "POST"
}'

See REST API for full JSON specification

String recordedExpectations = new MockServerClient("localhost", 1080)
    .retrieveRecordedExpectations(
        request()
            .withPath("/some/path")
            .withMethod("POST"),
        Format.JAVA
    );
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=JAVA" -d '{
    "path": "/some/path"
}'

See REST API for full JSON specification

String recordedExpectations = new MockServerClient("localhost", 1080)
    .retrieveRecordedExpectations(
        request()
            .withPath("/some/path")
            .withMethod("POST"),
        Format.JSON
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedExpectations({
    "path": "/some/path",
    "method": "POST"
}).then(
    function (recordedExpectations) {
        console.log(JSON.stringify(recordedExpectations));
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=JSON" -d '{
    "path": "/some/path"
}'

See REST API for full JSON specification

 

Retrieving Recorded Requests

All requests the MockServer receives are recorded, including both proxied requests and requests that have matched an expectation.

It is possible to retrieve the recorded requests, as show below in the code examples.

Requests are returned in the order they have been recorded. Which requests are returned can be filter using a request matcher.

HttpRequest[] recordedRequests = new MockServerClient("localhost", 1080)
    .retrieveRecordedRequests(
        request()
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
    .retrieveRecordedRequests({})
    .then(
        function (recordedRequests) {
            console.log(JSON.stringify(recordedRequests));
        },
        function (error) {
            console.log(error);
        }
    );

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS"

See REST API for full JSON specification

HttpRequest[] recordedRequests = new MockServerClient("localhost", 1080)
    .retrieveRecordedRequests(
        request()
            .withPath("/some/path")
            .withMethod("POST")
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedRequests({
    "path": "/some/path",
    "method": "POST"
}).then(
    function (recordedRequests) {
        console.log(JSON.stringify(recordedRequests));
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS" -d '{
    "path": "/some/path",
    "method": "POST"
}'

See REST API for full JSON specification

String recordedRequests = new MockServerClient("localhost", 1080)
    .retrieveRecordedRequests(
        request()
            .withPath("/some/path")
            .withMethod("POST"),
        Format.JAVA
    );
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS&format=JAVA" -d '{
    "path": "/some/path"
}'

See REST API for full JSON specification

String recordedRequests = new MockServerClient("localhost", 1080)
    .retrieveRecordedRequests(
        request()
            .withPath("/some/path")
            .withMethod("POST"),
        Format.JSON
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedRequests({
    "path": "/some/path",
    "method": "POST"
}).then(
    function (recordedRequests) {
        console.log(JSON.stringify(recordedRequests));
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS&format=JSON" -d '{
    "path": "/some/path"
}'

See REST API for full JSON specification

 

Retrieve Recorded Requests & Responses

All requests the MockServer receives are recorded, including both proxied requests and requests that have matched an expectation.

It is possible to retrieve the recorded requests and their responses, as show below in the code examples.

Requests and responses are returned in the order they have been recorded. Which requests are returned can be filter using a request matcher.

HttpRequestAndHttpResponse[] httpRequestAndHttpResponse = new MockServerClient("localhost", 1080)
    .retrieveRecordedRequestsAndResponses(
        request()
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
    .retrieveRecordedRequestsAndResponses({})
    .then(
        function (recordedRequestsAndResponses) {
            console.log(JSON.stringify(recordedRequestsAndResponses));
        },
        function (error) {
            console.log(error);
        }
    );

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES"

See REST API for full JSON specification

HttpRequestAndHttpResponse[] httpRequestAndHttpResponse = new MockServerClient("localhost", 1080)
    .retrieveRecordedRequestsAndResponses(
        request()
            .withPath("/some/path")
            .withMethod("POST")
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedRequestsAndResponses({
    "path": "/some/path",
    "method": "POST"
}).then(
    function (recordedRequestsAndResponses) {
        console.log(JSON.stringify(recordedRequestsAndResponses));
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES" -d '{
    "path": "/some/path",
    "method": "POST"
}'

See REST API for full JSON specification

 

Retrieving Recorded Logs

MockServer and the proxy record log messages for all major actions, including:

It is possible to retrieve the recorded log messages, as show below in the code examples.

Log messages are returned in the order they have been recorded, and which log messages are returned can be filter using a request matcher.

String logMessages = new MockServerClient("localhost", 1080)
    .retrieveLogMessages(
        request()
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
    .retrieveLogMessages({})
    .then(
        function (logMessages) {
            // logMessages is a String[]
            console.log(logMessages);
        },
        function (error) {
            console.log(error);
        }
    );

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=LOGS"

See REST API for full JSON specification

String logMessages = new MockServerClient("localhost", 1080)
    .retrieveLogMessages(
        request()
            .withPath("/some/path")
            .withMethod("POST")
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
    .retrieveLogMessages({
        "path": "/some/path",
        "method": "POST"
    })
    .then(
        function (logMessages) {
            // logMessages is a String[]
            console.log(logMessages);
        },
        function (error) {
            console.log(error);
        }
    );

See REST API for full JSON specification

curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=LOGS" -d '{
    "path": "/some/path",
    "method": "POST"
}'

See REST API for full JSON specification

String[] logMessages = new MockServerClient("localhost", 1080)
    .retrieveLogMessagesArray(
        request()
            .withPath("/some/path")
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
    .retrieveLogMessages({
        "path": "/some/path"
    })
    .then(
        function (logMessages) {
            // logMessages is a String[]
            console.log(logMessages);
        },
        function (error) {
            console.log(error);
        }
    );

See REST API for full JSON specification

 

Logging

All interactions with the MockServer are logged including setting up expectations, matching expectations, clearing expectations and verifying requests. The log can be particularly helpful when trying to debug why a test is failing or expectations are not being matched.

The following information is logged:

  • WARN - exceptions, errors
  • INFO - all interactions with the MockServer including setting up expectations, matching expectations, clearing expectations and verifying requests
  • DEBUG - all matcher results, including when specific matchers fail (such as HeaderMatcher)
  • TRACE - low level details or exceptions that aren't usually considered an error

The TRACE level logging results in a lot of verbose logging but can be very helpful to debug why a complex matcher (such as the JSON Schema matcher) is not matching.

To disable logging the following options can be used:

  • -Dmockserver.logLevel=OFF - to disable logging from the MockServer and Proxy classes
  • -Droot.logLevel=OFF - to disable all logging from all other classes

The following sections explain how to configure logging when running MockServer via:

 

Configuring logging for JUnit 4 @Rule, JUnit 5 Test Extension or Java API (i.e. maven or gradle project)

MockServer uses SL4J for logging so if MockSever is being launched using the JUnit 4 @Rule, the JUnit 5 Test Extension, ClientAndServer or directly using the org.mockserver.netty.MockServer the project launching MockServer needs to configure the logging output by configuring SLF4J. MockServer relies on a SLF4J binding being on the classpath for logs to be output. The simplest approach is to use the Java Logger SLF4J binding.

In MockServer the Java Logger SLF4J binding is only an optional dependency. Therefore, when MockServer is added as a dependency to a Maven or Gradle project it does not pull in the Java Logger binding transitively.

If no existing SLF4J logger binding exists no logs will be output and the following error will be displayed by SLF4J:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

If this happens the simplest way to output logs for MockServer is to add the Java Logger SLF4J binding as a dependency. For example, in Maven this would be as follows:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-jdk14</artifactId>
    <version>1.7.29</version>
</dependency>

It is possible to configure the logger using a configuration file by specifying the java.util.logging.config.file system property, as follows.

-Djava.util.logging.config.file=/path/to/example_logging_configuration.properties

It is possible to configure the logger programmatically, for example, as follows.

ConfigurationProperties.logLevel("DEBUG");
String loggingConfiguration = "" +
    "handlers=org.mockserver.logging.StandardOutConsoleHandler\n" +
    "org.mockserver.logging.StandardOutConsoleHandler.level=ALL\n" +
    "org.mockserver.logging.StandardOutConsoleHandler.formatter=java.util.logging.SimpleFormatter\n" +
    "java.util.logging.SimpleFormatter.format=%1$tF %1$tT  %3$s  %4$s  %5$s %6$s%n\n" +
    ".level=" + javaLoggerLogLevel() + "\n" +
    "io.netty.handler.ssl.SslHandler.level=WARNING";
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(loggingConfiguration.getBytes(UTF_8)));
 

Configuring logging via the Command Line

When running MockServer directly from the command line the command line argument -logLevel can be used to set the log level, as follows:

java -jar ~/Downloads/mockserver-netty-5.14.0-shaded.jar -serverPort 1080 -logLevel DEBUG

Alternatively a system property mockserver.logLevel can be used to set the log level, as follows:

java -Dmockserver.logLevel=INFO -jar ~/Downloads/mockserver-netty-5.14.0-shaded.jar -serverPort 1080

Configuring Java Logger

When running MockServer from the command line it relies on the Java Logger java.util.logging.Logger in addition to controlling the log level of MockServer using -logLevel the underlying logging framework can be configured (overriding the default configuration) by specifying the System Property java.util.logging.config.file or java.util.logging.config.class as detailed in the LogManager JavaDoc.

The MockServer github repository contains an example Java Logger configuration file (which would be configured using java.util.logging.config.file).

The default logging configuration can be overridden as follows:

java -Djava.util.logging.config.file=/path/to/example_logging_configuration.properties -jar ~/Downloads/mockserver-netty-5.14.0-shaded.jar -serverPort 1080 -logLevel DEBUG
 

Configuring logging via the Maven Plugin

The mockserver-maven-plugin provides a logLevel settings that can be used to define the log level for all MockServer classes, as follows:

<plugin>
     <groupId>org.mock-server</groupId>
     <artifactId>mockserver-maven-plugin</artifactId>
     <version>5.14.0</version>
     <configuration>
        <serverPort>1080</serverPort>
        <logLevel>DEBUG</logLevel>
     </configuration>
     <executions>
         <execution>
             <id>process-test-classes</id>
             <phase>process-test-classes</phase>
             <goals>
                 <goal>runForked</goal>
             </goals>
         </execution>
         <execution>
             <id>verify</id>
             <phase>verify</phase>
             <goals>
                 <goal>stopForked</goal>
             </goals>
         </execution>
     </executions>
 </plugin>
 

Configuring logging via the npm module

When running MockServer using the mockserver-node Grunt plugin and Node.js (npm) module the verbose option can be used to enable INFO level logging and the trace option can be used to enable TRACE level logging.

It is generally recommended to enable verbose which should provide the correct amount of information, trace is only required for very low level debugging.

var mockserver = require('mockserver-node');

mockserver
    .start_mockserver({
        serverPort: 1080,
        verbose: true,
        trace: true
    })
    .then(
        function () {
            console.log("started MockServer");
        },
        function (error) {
            console.log(JSON.stringify(error));
        }
    );

Configuring logging via the Grunt plugin

When running MockServer using the mockserver-node as a Grunt plugin module the verbose option can be used to enable INFO level logging and the trace option can be used to enable TRACE level logging. The --verbose command line flag can also be used to enable the mockserver-node verbose option from the command line.

It is generally recommended to enable verbose which should provide the correct amount of information, trace is only required for very low level debugging.

grunt.initConfig({
        start_mockserver: {
            options: {
                serverPort: 1080,
                verbose: true,
                trace: true
            }
        },
        stop_mockserver: {
            options: {
                serverPort: 1080
            }
        }
});

grunt.loadNpmTasks('mockserver-node');