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.