Mockito Exception - when() 需要一个参数,该参数必须是 mock 上的方法调用

2022-08-31 16:34:17

我有一个非常简单的测试用例,它使用Mockito和Spring Test框架。当我这样做

when(pcUserService.read("1")).thenReturn(pcUser);

我得到这个例外。

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.

    at com.project.cleaner.controller.test.PcUserControllerTest.shouldGetPcUser(PcUserControllerTest.java:93)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)

我尝试了不同的方法,但不断收到此错误消息。我正在使用Spring 3.1.0.RELEASE和Mockito。请分享并指导我朝着正确的方向前进。


答案 1

您需要先创建 pcUserService 的 MOCK,然后使用该模拟。

PcUserService mock = org.mockito.Mockito.mock(PcUserService.class);
when(mock.read("1")).thenReturn(pcUser);

答案 2

万一其他人遇到这个问题....

也可能是您尝试模拟的方法被声明为方法的情况。从我注意到的情况来看,这似乎会导致Mockito出现问题。pcUserService.readfinal