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

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.

Tags:

Java

Junit