Come deridere un server Web per test unitari in Java?
Domanda
Vorrei creare un test unitario usando un server web finto. Esiste un server Web scritto in Java che può essere facilmente avviato e arrestato da un caso di test JUnit?
Soluzione
Prova Simple ( Maven ) è molto facile da integrare in un test unitario. Prendi il RoundTripTest ed esempi come PostTest scritto con Simple. Fornisce un esempio di come incorporare il server nel test case.
Anche Simple è molto più leggero e veloce di Jetty, senza dipendenze. Quindi non dovrai aggiungere più file jar sul tuo percorso di classe. Né dovrai preoccuparti di WEB-INF / web.xml
o di altri artefatti.
Altri suggerimenti
Wire Mock sembra offrire un solido set di matrici e mock per testare servizi web esterni.
@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));
}
Può integrarsi anche con Spock. Esempio trovato qui .
Stai cercando di utilizzare un mock o un incorporato server web?
Per un mock web server, prova a utilizzare Mockito , o qualcosa di simile e prendi semplicemente in giro gli oggetti HttpServletRequest
e HttpServletResponse
come:
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());
Per un server Web incorporato , puoi utilizzare Jetty , che puoi utilizzare nei test .
Puoi anche scrivere un mock con la classe HttpServer
di JDK (non sono necessarie dipendenze esterne). Vedi questo post del blog specificando come.
In sintesi:
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);
}
Un'altra buona alternativa sarebbe MockServer ; fornisce un'interfaccia fluida con la quale è possibile definire il comportamento del server Web deriso.
Puoi provare Jadler che è una libreria con un'API Java programmatica fluente per stub e finto risorse http nei test. Esempio:
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");
Se stai usando apache HttpClient, questa sarà una buona alternativa. HttpClientMock
HttpClientMock httpClientMock = new httpClientMock()
HttpClientMock("http://example.com:8080");
httpClientMock.onGet("/login?user=john").doReturnJSON("{permission:1}");
Prova a utilizzare il server Web Jetty .
Dai un'occhiata a https://github.com/oharsta/priproba