首页 > 解决方案 > Mockito 3.7:MockStatic 失败并显示消息:0 Matchers Expected, 1 Recorded InvalidUseOfMatchersException

问题描述

我试图在 Mockito 中模拟一个静态函数,如下所示:

    @ExtendWith(MockitoExtension.class)
    public class MyTest {
        MockedStatic<MyStaticClass> myStaticClassMock;
        @Mock
        MyClient myClientMock;
   
        @BeforeEach
        public void setup() {
             myStaticClassMock= Mockito.mockStatic(MyStaticClass.class);
             myStaticClassMock.when(() -> MyStaticClass.getClient()).thenReturn(this.myClientMock);
             ...
        }

        @Test
        public void someTest() {
            ...
            this.classUnderTest.someFunction(); //Error here because MyStaticClass.getClient() call fails.
            ...
        }  

在运行我的测试类时,我最终InvalidUseOfMatchersException: 0 Matchers Expected, 1 Recorded...MyStaticClass.getClient()调用我正在测试的函数。更奇怪的是,如果我在我的 IDE 中调试测试,测试将通过并且模拟的静态函数将正确返回模拟。

这是使用 JDK 11、Mockito 3.7.7 编写的。有什么我做错了吗?

标签: mockitojunit5

解决方案


推荐阅读