首页 > 解决方案 > 如何模拟 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中模拟静态方法,外部类不起作用但我创建的内部类是正常的。

标签: unit-testingjunitmockingmockito

解决方案


推荐阅读