Java에서 단위 테스트를 위해 웹 서버를 조롱하는 방법은 무엇입니까?
문제
모의 웹 서버를 사용하여 단위 테스트를 만들고 싶습니다. Java로 작성된 웹 서버가 Junit 테스트 케이스에서 쉽게 시작하고 중단 할 수 있습니까?
다른 팁
와이어 모의 외부 웹 서비스를 테스트하기위한 견고한 스텁과 모의 세트를 제공하는 것 같습니다.
@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과도 통합 될 수 있습니다. 발견 된 예 여기.
당신은 사용하려고합니까? 모조품 또는 내장 웹 서버?
a 모조품 웹 서버, 사용해보십시오 모키토, 또는 비슷한 것, 그리고 그냥 조롱하십시오 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; 조롱 된 웹 서버의 동작을 정의 할 수있는 유창한 인터페이스를 제공합니다.
당신은 시도 할 수 있습니다 Jadler 이는 테스트에서 HTTP 리소스를 스터브하고 조롱하는 유창한 프로그래밍 방식 Java API가있는 라이브러리입니다. 예시:
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}");
사용해보십시오 부두 웹 서버.
제휴하지 않습니다 StackOverflow