简体   繁体   中英

How to use ArgumentCaptor to verify bytes written to HttpServletResponse

I have a controller that provides functionality to download the 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 am not able to figure out how to write test where I can verify the contents which were written to response . I have used ArgumentCaptor lot but somehow it doesn't seem to fit here.

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

As suggested by David, I was able to do so.

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())));

一种方法是模拟response及其输出流,然后验证对模拟输出流的write方法的调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM