Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito and HttpServletResponse - write output to textfile

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.

like image 664
jan Avatar asked Apr 25 '14 11:04

jan


2 Answers

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");
like image 182
Jonathan Avatar answered Sep 20 '22 08:09

Jonathan


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();
}
like image 39
PCalouche Avatar answered Sep 22 '22 08:09

PCalouche