質問
モックWebサーバーを使用して単体テストを作成したいと思います。 JUnitテストケースから簡単に起動および停止できる、Javaで記述されたWebサーバーはありますか?
他のヒント
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));
}
スポックとも統合できます。例がこちらで見つかりました。
模擬または埋め込みを使用しようとしている Webサーバー?
モック Webサーバーの場合、 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 を試すことができます。これは流fluentなプログラム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 Webサーバーを使用してみてください。
所属していません StackOverflow