I would like to create a unit test using a mock web server. Is there a web server written in Java which can be easily started and stopped from a JUnit test case?
MockServer can be run:using a JUnit 4 @Rule via a @Rule annotated field in a JUnit 4 test. using a JUnit 5 Test Extension via a @ExtendWith annotated JUnit 5 class. using a Spring Test Execution Listener via a @MockServerTest annotated test class. as a Docker container in any Docker enabled environment.
EasyMock. EasyMock is also a mocking framework that can be effectively used in unit tests.
What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With