题
我想使用模拟Web服务器创建单元测试。是否有一个用Java编写的Web服务器,可以从JUnit测试用例中轻松启动和停止?
其他提示
Wire Mock 似乎提供了一组可靠的存根和模拟来测试外部Web服务。
@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));
}
它也可以与spock集成。示例此处。
您是否尝试使用 模拟或嵌入式 网络服务器?
对于模拟网络服务器,请尝试使用 Mockito ,或类似的东西,只需模拟 HttpServletRequest
和 HttpServletResponse
对象,如:
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());
您也可以使用JDK的 HttpServer
类编写模拟(不需要外部依赖项)。请参见此博文详细说明如何。
总结:
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);
}
另一个不错的选择是 MockServer ;它提供了一个流畅的界面,您可以使用该界面定义模拟的Web服务器的行为。
您可以尝试 Jadler ,这是一个具有流畅的编程Java API的库在测试中存根和模拟http资源。例如:
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");
如果您使用的是apache HttpClient,这将是一个不错的选择。 HttpClientMock
HttpClientMock httpClientMock = new httpClientMock()
HttpClientMock("http://example.com:8080");
httpClientMock.onGet("/login?user=john").doReturnJSON("{permission:1}");
尝试使用 Jetty网络服务器。
不隶属于 StackOverflow