Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

junit

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?

like image 396
jon077 Avatar asked Mar 03 '09 13:03

jon077


People also ask

How do I use MockServer in JUnit?

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.

What mocking frameworks have you used for unit testing in Java?

EasyMock. EasyMock is also a mocking framework that can be effectively used in unit tests.

What can be mocked for unit testing?

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.


2 Answers

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.

like image 135
keaplogik Avatar answered Sep 23 '22 01:09

keaplogik


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.

like image 29
Gene Gotimer Avatar answered Sep 22 '22 01:09

Gene Gotimer