Mockito 异常 - when() 需要一个参数,该参数必须是模拟上的方法调用 [英] Mockito Exception - when() requires an argument which has to be a method call on a mock

查看:81
本文介绍了Mockito 异常 - when() 需要一个参数,该参数必须是模拟上的方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very simple test case that is using Mockito and Spring Test framework. When I do

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)

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

I have tried with different methods but keep on getting this error message. I am using Spring 3.1.0.RELEASE with Mockito. Please share and guide me in the right direction.

推荐答案

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

You need to create a MOCK of pcUserService first, and then use that mock.

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

这篇关于Mockito 异常 - when() 需要一个参数,该参数必须是模拟上的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆