java - 如何从 MockMultipartFile 在 Spring MVC 测试中生成异常?
问题描述
我正在尝试为 Spring MVC 中的控制器编写一些单元测试,并且部分控制器方法具有以下代码:
try {
newProjectFile.setFileType(fileType);
newProjectFile.setContent(BlobProxy.generateProxy(file.getInputStream(), file.getSize()));
} catch (Exception e) {
throw new BadUpdateException(e.getMessage());
}
我在我的单元测试中设置了一个 MockMultipartFile ,并想在这里测试异常情况,以便我可以获得错误的请求响应。
我尝试设置如下内容:
单元测试:
MockMultipartFile file = new MockMultipartFile("file", "receipts.zip", "application/zip", "".getBytes());
[...]
when(file.getInputStream()).thenThrow(IOException.class);
[...]
我收到以下错误:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
如果我不能像使用任何普通的模拟对象一样在 MockMultipartFile 上使用“何时”,并且 Mockito 不允许您模拟静态方法,我怎样才能在此处抛出异常?
编辑:如评论中所述,MockMultipartFile 不是来自 Mockito,因此出现上述错误。
问题实际上是如何在 try/catch 块中引发异常,这可能是通过在 file.getInputStream() 上引发 IOException 或在 BlobProxy.generateProxy() 上引发 UnsupportedOperationException,以便我的方法引发 BadUpdateException。
解决方案
所以我的同事找到了一个使用匿名内部类来解决这个问题的好方法:
@Override
public InputStream getInputStream() throws IOException {
throw new IOException();
}
};
这意味着当试图从 MockMultipartFile 中获取 InputStream 时,控制器方法中的 try/catch 块中会抛出异常,结果是 BadUpdateException。
推荐阅读
- sql - 使用子查询 Woo Commerce 创建 SQL
- python - 即使在调试之后,Kivymd 应用程序也会在启动时崩溃
- javascript - Sprite 框架作为 div 背景,在 div 旋转时自动缩放错误
- sql-server - t sql 字符串中第一个数字的所有权利
- postgresql - SQL 查询不适用于 PostgreSQL 命令
- android - 在领域中创建了两个表,但保存的数据仅在领域中的第一个表中
- python - 自定义不和谐状态不断收到此错误
- reactjs - React 中的解耦(带钩子)
- javascript - 如何从 Web 应用程序在点阵打印机中获得所需的输出?
- reactjs - 无法在 MongoDB (MERN) 中读取 _id 属性