例外:mockito想要但未被调用,实际上与这个模拟没有任何交互 [英] Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

查看:3966
本文介绍了例外:mockito想要但未被调用,实际上与这个模拟没有任何交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接口

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通缉但不是调用,实际上在验证调用时与此模拟没有交互。

任何人都可以提出一些解决方案。

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 <是更明智的选择/ p>

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想要但未被调用,实际上与这个模拟没有任何交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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