【发布时间】:2017-07-31 15:38:33
【问题描述】:
我正在尝试使用 MockitoJUnitRunner 编写 JUnit。 我正在将文件 ID 传递给我的函数,该函数正在从云下载文件并将 zip 文件作为下载返回。 这是我的代码
public void getLogFile(HttpServletResponse response, String id) throws IOException {
response.setContentType("Content-type: application/zip");
response.setHeader("Content-Disposition", "attachment; filename=LogFiles.zip");
ServletOutputStream out = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out));
zos.putNextEntry(new ZipEntry(id));
InputStream inputStream = someDao.getFile(id);
BufferedInputStream fif = new BufferedInputStream(inputStream);
int data = 0;
while ((data = fif.read()) != -1) {
zos.write(data);
}
fif.close();
zos.closeEntry();
zos.close();
}
而我的 JUnit 函数是
@Mock
private MockHttpServletResponse mockHttpServletResponse;
anyInputStream = new ByteArrayInputStream("test data".getBytes());
@Test
public void shouldDownloadFile() throws IOException {
ServletOutputStream outputStream = mock(ServletOutputStream.class);
when(mockHttpServletResponse.getOutputStream()).thenReturn(outputStream);
=> when(someDao.download(anyString())).thenReturn(anyInputStream);
controller.getLogFile(mockHttpServletResponse, id);
verify(mockHttpServletResponse).setContentType("Content-type: application/zip");
verify(mockHttpServletResponse).setHeader("Content-Disposition","attachment; filename=LogFiles.zip");
verify(atmosdao).download(atmosFilePath);
}
这个单元测试通过了,但是我想验证 outputStream 上写了什么,我该怎么做?当我将“测试数据”写入模拟的 outputStream 时,就像
anyInputStream = new ByteArrayInputStream("test data".getBytes());
when(someDao.download(anyString())).thenReturn(anyInputStream);
mockHttpServletResponse.getContentAsString() 给我 null !
是否可以断言使用 zipoutputStream 编写的MockHttpServletResponse?如果是,那我该怎么做?
谢谢。
【问题讨论】:
标签: java unit-testing junit mockito spring-test-mvc