Example Code - Java
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.