How to use ArgumentCaptor to check for bytes written in HttpServletResponse

I have a controller that provides functionality for downloading a file.

@ResponseBody
public void downloadRecycleResults(String batchName, HttpServletResponse response) throws Exception {
    File finalResultFile = null;
    // code here generates and initializes finalResultFile for batchName
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=" + finalResultFile.getName());
    IOUtils.copy(new FileReader(finalResultFile), response.getOutputStream());
}

I can’t understand how to write a test, where I can check the content that was written on response. I used the ArgumentCaptorlot, but somehow it does not fit here.

controller.downloadRecycleResults("batchName", mock(HttpServletResponse.class));
verify(response).getOutputStream(); // but how to capture content?
+2
source share
2 answers

One way to do this is to mock responseand its output stream, and then check the method calls of writeyour mocked output stream.

+2
source

As David suggested, I was able to do this.

ServletOutputStream opStreamMock = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(opStreamMock);

ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class);
verify(opStreamMock).write(captor.capture(), Mockito.anyInt(), Mockito.anyInt());

//can create reader now.
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(captor.getValue())));
+6
source

All Articles