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

2022-01-14 00:00:00 unit-testing mockito java

我有界面

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"));
}

相关文章