unit-testing - 如何模拟 EasyExcel.create(),一个使用 mockito 的静态方法
问题描述
这是我的 UT 代码:
@Test
void downloadTemplateThrowingExceptionTest() throws Exception {
try(MockedStatic<EasyExcel> mockEasyExcel = Mockito.mockStatic(EasyExcel.class)){
mockEasyExcel.when(()->EasyExcel.write(any(ServletOutputStream.class), eq(ExcelAgentCodeFileDTO.class))).thenThrow(new WritingException());
writerTemplate.run();
}
}
下面是 EasyExcel.class 中的静态方法:
public static ExcelWriterBuilder write(OutputStream outputStream, Class head) {
ExcelWriterBuilder excelWriterBuilder = new ExcelWriterBuilder();
excelWriterBuilder.file(outputStream);
if (head != null) {
excelWriterBuilder.head(head);
}
return excelWriterBuilder;
}
然后得到这个异常:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at com.*****.***.controller.***ControllerTest.lambda$downloadTemplateThrowingExceptionTest$5(***ControllerTest.java:460)
-> at com.*****.***.controller.***ControllerTest.lambda$downloadTemplateThrowingExceptionTest$5(***ControllerTest.java:460)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
但是,我新建了一个新类“EasyExcelNew.class”,如下所示:
public class EasyExcelNew {
...
public static ExcelWriterBuilder write(OutputStream outputStream, Class head) {
ExcelWriterBuilder excelWriterBuilder = new ExcelWriterBuilder();
excelWriterBuilder.file(outputStream);
if (head != null) {
excelWriterBuilder.head(head);
}
return excelWriterBuilder;
}
...
}
我用EasyExcelNew替换EasyExcel,它工作正常,单元测试通过。我很困惑为什么在EasyExcel中模拟静态方法,外部类不起作用但我创建的内部类是正常的。
解决方案
推荐阅读
- database - 卡蒙达数据库。保存 id 而不是对象
- sql - ORA-01417 - 两个外部连接错误。新的连接语法?
- c# - 如何在winforms中打印列或行跨越的datagridview
- javascript - Angular 8 从其上下文之外访问数据并检测更改
- python - 如何通过 python 脚本修改网页浏览历史?
- python - 如何正确连接两个一维数组而不展平?
- php - 插入新图像后如何从上传文件夹中删除旧图像
- typescript - 扩展另一个内部类的 TypeScript 内部类不可分配给超类(声明合并)
- python - 嵌套 if 用于带有模式的变量名
- json - 如何从 OpenAPI 3.0 规范生成 JSON 示例