Mockito Exception - when()需要一个必须是模拟方法调用的参数

jsf*_*jsf 35 java controller spring-test mockito

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

when(pcUserService.read("1")).thenReturn(pcUser);
Run Code Online (Sandbox Code Playgroud)

我得到了这个例外.

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)
Run Code Online (Sandbox Code Playgroud)

我尝试过不同的方法,但继续收到此错误消息.我正在使用Spring 3.1.0.RELEASE和Mockito.请分享并指导我正确的方向.

Ral*_*lph 40

您需要首先创建一个pcUserService的MOCK,然后使用该模拟.

PcUserService mock = org.mockito.Mockito.mock(PcUserService.class);
when(mock.read("1")).thenReturn(pcUser);
Run Code Online (Sandbox Code Playgroud)

  • 是的,我面临一个问题,我有一个服务,比如说“TestService”,它有一个方法“testMethod()”,“testMethod”内的代码包括对另一个服务方法的调用,例如。`AnotherTestService.getData()`。所以就我而言,我无法模拟 `AnotherTestService` 我应该做什么? (2认同)

djk*_*y99 22

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

也可能是您尝试模拟pcUserService.readfinal方法被声明为方法.从我注意到这似乎导致Mockito的问题.

  • 诊断没问题,但解决方案是什么:p (3认同)
  • 实际上,有时您不会模拟自己的类,而是模拟外部依赖项中的某些类。但没关系我发现如何用mockito模拟最终方法/sf/ask/1000500441/ (2认同)

Coo*_*ind 8

如果使用Kotlin,则应该知道final默认情况下是方法。所以写open fun而不是fun。感谢@ djkelly99的提示。


Sar*_*ran 7

此问题的另一个解决方案可能是,如果测试类正在使用PowerMockRunner,您可能必须在@PrepareForTest注释中将要模拟的类添加到列表中。

例如 -

@PrepareForTest({ PcUserService.class })


Nin*_*ale 5

就我而言,它是通过注入解决的@MockBean

对于前。

@MockBean
StateRepository mockStateRepository;
Run Code Online (Sandbox Code Playgroud)