Question

I want to test my servlet using mockito. I also want to know what the server output is. So if the servlet writes something out like this:

HttpServletResponse.getWriter().println("xyz");

I want to write it to a textfile instead. I created the mock for the HttpServletResponse and tell Mockito it should return my custom PrintWriter if HttpServletResponse.getWriter() is called:

HttpServletResponse resp = mock(HttpServletResponse.class);
PrintWriter writer = new PrintWriter("somefile.txt");
when(resp.getWriter()).thenReturn(writer);

The textfile is generated, but it is empty. How can I get this working?

Edit:

@Jonathan: Thats actually true, mocking the writer as well is a much cleaner solution. Solved it like that

StringWriter sw = new StringWriter();
PrintWriter pw  =new PrintWriter(sw);

when(resp.getWriter()).thenReturn(pw);

Then I can just check the content of the StringWriter and does not have to deal with files at all.

Was it helpful?

Solution 2

To see any output with the PrintWriter you need to close() or flush() it.

Alternatively you can create the PrintWriter with the autoFlush parameter, e.g.:

final FileOutputStream fos = new FileOutputStream("somefile.txt");
final PrintWriter writer = new PrintWriter(fos, true); // <-- autoFlush

This will write to the file when println, printf or format is invoked.

I would say closing the PrintWriter is preferable.

Aside:

Have you considered mocking the Writer? You could avoid writing to a file and verify the expected calls instead, e.g.:

verify(writer).println("xyz");

OTHER TIPS

If you happen to be using Spring then it has a MockHttpServletResponse class.

@Test
public void myTest() {
    MockHttpServletResponse response = new MockHttpServletResponse();
    // Do test stuff here
    // Verify what was written to the response using MockHttpServletResponse's methods
    response.getContentAsString();
    response.getContentAsByteArray();
    response.getContentLength();
}

I know this is a late answer, but I just figured out a way to do this (without having to write to a file). We could use org.springframework.mock.web.MockHttpServletResponse.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top