例外:mockito 想要但没有被调用,实际上与这个 mock 的交互为零

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock(例外:mockito 想要但没有被调用,实际上与这个 mock 的交互为零)
本文介绍了例外:mockito 想要但没有被调用,实际上与这个 mock 的交互为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有界面

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 的交互为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)