How to mock a web server for unit testing in Java? [closed]

Wire Mock seems to offer a solid set of stubs and mocks for testing external web services.

@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);


@Test
public void exactUrlOnly() {
    stubFor(get(urlEqualTo("/some/thing"))
            .willReturn(aResponse()
                .withHeader("Content-Type", "text/plain")
                .withBody("Hello world!")));

    assertThat(testClient.get("/some/thing").statusCode(), is(200));
    assertThat(testClient.get("/some/thing/else").statusCode(), is(404));
}

It can integrate with spock as well. Example found here.


Are you trying to use a mock or an embedded web server?

For a mock web server, try using Mockito, or something similar, and just mock the HttpServletRequest and HttpServletResponse objects like:

MyServlet servlet = new MyServlet();
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);

StringWriter out = new StringWriter();
PrintWriter printOut = new PrintWriter(out);
when(mockResponse.getWriter()).thenReturn(printOut);

servlet.doGet(mockRequest, mockResponse);

verify(mockResponse).setStatus(200);
assertEquals("my content", out.toString());

For an embedded web server, you could use Jetty, which you can use in tests.


You can write a mock with the JDK's com.sun.net.httpserver.HttpServer class as well (no external dependencies required). See this blog post detailing how.

In summary:

HttpServer httpServer = HttpServer.create(new InetSocketAddress(8000), 0); // or use InetSocketAddress(0) for ephemeral port
httpServer.createContext("/api/endpoint", new HttpHandler() {
   public void handle(HttpExchange exchange) throws IOException {
      byte[] response = "{\"success\": true}".getBytes();
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
      exchange.getResponseBody().write(response);
      exchange.close();
   }
});
httpServer.start();

try {
// Do your work...
} finally {
   httpServer.stop(0); // or put this in an @After method or the like
}

Try Simple(Maven) its very easy to embed in a unit test. Take the RoundTripTest and examples such as the PostTest written with Simple. Provides an example of how to embed the server into your test case.

Also Simple is much lighter and faster than Jetty, with no dependencies. So you won't have to add several jar files onto your classpath. Nor will you have to be concerned with WEB-INF/web.xml or any other artifacts.