Mockito and HttpServletResponse - write output to a text file

I want to test my servlet with mockito. I also want to know what a server is. So, if the servlet writes something like this:

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

I want to write it to a text file. I created a layout for the HttpServletResponse and told Mockito that 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); 

A text file is created, but it is empty. How can I make this work?

Edit:

@Jonathan: Actually it's true, mocking a writer, this is a much cleaner solution. Decided so.

 StringWriter sw = new StringWriter(); PrintWriter pw =new PrintWriter(sw); when(resp.getWriter()).thenReturn(pw); 

Then I can just check the contents of StringWriter and not deal with files at all.

+6
source share
2 answers

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

Alternatively, you can create a PrintWriter with the autoFlush parameter , for example:

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

This will be written to the file when println , printf or format called.

I would say closing PrintWriter preferable.

To the side:

Do you find Writer mockery? You can avoid writing to a file and instead check for expected calls, for example:

 verify(writer).println("xyz"); 
+2
source

If you use Spring, then it has the MockHttpServletResponse class.

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

All Articles