tags:

views:

531

answers:

3

I would like to create a unit test using a mock web server. Is there a web server written in java which can be easily started and stopped from a junit test case?

+4  A: 

try jetty web server

flybywire
+1  A: 

Try Simple its very easy to embed in a unit test. Take the RoundTripTest and examples such as the PostTest written with Simple. Provides an example of how to embed the server in to your test case.

Also Simple is much lighter and faster than Jetty, with no dependancies. So you won't have to add several jars on to your classpath. Nor will you have to be concerned with WEB-INF/web.xml or any other artifacts.

ng
+1  A: 

Are you trying to use a mock web server, or an embedded web server?

For a mock, try using mockito (http://code.google.com/p/mockito/) or something similar and just mock the HttpServletRequest and 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());

Embedded, you could use Jetty (http://www.mortbay.org/jetty/). See http://docs.codehaus.org/display/JETTY/ServletTester for an explanation of using it in tests.

CoverosGene