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?
问题:
回答1:
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 jars on to your classpath. Nor will you have to be concerned with WEB-INF/web.xml
or any other artifacts.
回答2:
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.
回答3:
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.
回答4:
Another good alternative would be MockServer; it provides a fluent interface with which you can define the behaviour of the mocked web server.
回答5:
You can try Jadler (http://jadler.net) which is a library with a fluent programmatic Java API to stub and mock http resources in your tests. Example:
onRequest() .havingMethodEqualTo("GET") .havingPathEqualTo("/accounts/1") .havingBody(isEmptyOrNullString()) .havingHeaderEqualTo("Accept", "application/json") .respond() .withDelay(2, SECONDS) .withStatus(200) .withBody("{\\"account\\":{\\"id\\" : 1}}") .withEncoding(Charset.forName("UTF-8")) .withContentType("application/json; charset=UTF-8");
回答6:
You can write a mock with the JDK's HttpServer
class as well (no external dependencies required). See this blog post detailing how.
In summary:
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8000), 0); 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); }
回答7:
Try using the Jetty web server.
回答8:
Have a look at https://github.com/oharsta/priproba
回答9:
If you are using apache HttpClient, This will be a good alternative. HttpClientMock
HttpClientMock httpClientMock = new httpClientMock() HttpClientMock("http://example.com:8080"); httpClientMock.onGet("/login?user=john").doReturnJSON("{permission:1}");
FULL DISCLOSURE: I am the author of the library.