Reputation: 4053
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.
Upvotes: 13
Views: 15964
Reputation: 74
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
.
Upvotes: -1
Reputation: 1645
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();
}
Upvotes: 9
Reputation: 20375
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");
Upvotes: 5