我想使用模拟Web服务器创建单元测试。是否有一个用Java编写的Web服务器,可以从JUnit测试用例中轻松启动和停止?

有帮助吗?

解决方案

尝试简单 Maven )它非常容易嵌入单元测试中。参加RoundTripTest和例如 PostTest 。提供如何将服务器嵌入测试用例的示例。

此外,Simple比Jetty更轻,更快,没有依赖性。因此,您不必在类路径中添加几个jar文件。您也不必关心 WEB-INF / web.xml 或任何其他工件。

其他提示

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());

对于嵌入式网络服务器,您可以使用 Jetty ,你可以在测试中使用

您也可以使用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网络服务器

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top