如何使用ArgumentCaptor验证写入HttpServletResponse的字节 [英] How to use ArgumentCaptor to verify bytes written to HttpServletResponse

查看:203
本文介绍了如何使用ArgumentCaptor验证写入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());
}

我无法弄清楚如何编写测试我可以在哪里验证写入回复的内容。我使用了 ArgumentCaptor 很多但不知道它似乎不适合这里。

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?


推荐答案

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

One way to do this would be to mock both response and its output stream, then verify calls to the write method of your mocked output stream.

这篇关于如何使用ArgumentCaptor验证写入HttpServletResponse的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆