gpt4 book ai didi

java - 如何在 zipoutputstream 中断言响应

转载 作者:行者123 更新时间:2023-11-30 02:37:19 35 4
gpt4 key购买 nike

我正在尝试使用 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上写入的内容,我该怎么做?当我将“测试数据”写入模拟的输出流时,例如

anyInputStream = new ByteArrayInputStream("test data".getBytes());

when(someDao.download(anyString())).thenReturn(anyInputStream);

mockHttpServletResponse.getContentAsString() 给我 null !

是否可以断言使用 zipoutputStream 编写的 MockHttpServletResponse ?如果是的话我该怎么做?

谢谢。

最佳答案

您可以创建一个自定义的输出流,而不是模拟您的 OutputStream:

public class CustomOutputStream extends ServletOutputStream {
private ByteArrayOutputStream out = new ByteArrayOutputStream();
private String content;

@Override
public void write(int b) throws IOException {
out.write(b);
}

@Override
public void close() throws IOException {
content = new String(out.toByteArray());
out.close();
super.close();
}

public String getContentAsString() {
return this.content;
}
}

此类将存储写入其中的所有字节并将它们保存在 content 字段中。

然后你替换这个:

ServletOutputStream outputStream = mock(ServletOutputStream.class);

通过这个:

CustomOutputStream outputStream = new CustomOutputStream();

当您的 servlet 调用 getOutputStream() 时,它将使用自定义的,最后 getContentAsString() 将返回写入您的 servlet 的输出.

注意:输出被压缩,因此字符串将包含奇怪的字符。如果您想要原始字符串,则必须解压缩它(在这种情况下,我将使用 out.toByteArray() 返回的字节数组而不是字符串,因为当您创建一个这样的字符串在调用 string.getBytes()) 时可能会遇到编码问题

关于java - 如何在 zipoutputstream 中断言响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42715903/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com