Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock(例外:mockito 想要但没有被调用,实际上与这个 mock 的交互为零)
问题描述
我有界面
Interface MyInterface {
myMethodToBeVerified (String, String);
}
接口的实现是
class MyClassToBeTested implements MyInterface {
myMethodToBeVerified(String, String) {
…….
}
}
我还有一门课
class MyClass {
MyInterface myObj = new MyClassToBeTested();
public void abc(){
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
}
我正在尝试为 MyClass 编写 JUnit.我已经完成了
I am trying to write JUnit for MyClass. I have done
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
但是我得到 mockito 想要但没有被调用,实际上在验证调用时与这个 mock 的交互为零.
谁能提出一些解决方案.
can anyone suggest some solutions.
推荐答案
你需要在你正在测试的类中注入 mock.目前,您正在与真实对象进行交互,而不是与模拟对象进行交互.您可以通过以下方式修复代码:
You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:
void testAbc(){
myClass.myObj = myInteface;
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
虽然将所有初始化代码提取到 @Before
although it would be a wiser choice to extract all initialization code into @Before
@Before
void setUp(){
myClass = new myClass();
myClass.myObj = myInteface;
}
@Test
void testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
这篇关于例外:mockito 想要但没有被调用,实际上与这个 mock 的交互为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:例外:mockito 想要但没有被调用,实际上与这个 mock 的交互为零


基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01