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

问题描述 投票:0回答:6

我有接口

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。我已经做到了

class MyClassTest {
    MyClass myClass = new MyClass();
  
    @Mock
    MyInterface myInterface;

    testAbc(){
         myClass.abc();
         verify(myInterface).myMethodToBeVerified(new String(“a”), new String(“b”));
    }
}

但是我需要 mockito 但没有被调用,实际上在验证调用时与此模拟的交互为零。

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

java unit-testing mockito
6个回答
31
投票
您需要在您正在测试的类中注入模拟。目前,您正在与真实对象交互,而不是与模拟对象交互。您可以通过以下方式修复代码:

void testAbc(){ myClass.myObj = myInteface; myClass.abc(); verify(myInterface).myMethodToBeVerified(new String("a"), new String("b")); }

尽管将所有初始化代码提取到

@Before

中会是一个更明智的选择

@Before void setUp(){ myClass = new myClass(); myClass.myObj = myInteface; } @Test void testAbc(){ myClass.abc(); verify(myInterface).myMethodToBeVerified(new String("a"), new String("b")); }
    

10
投票
您的班级

MyClass

创建一个新的
MyClassToBeTested
,而不是使用您的模拟。 
我在 Mockito wiki 上的文章描述了两种处理此问题的方法。


8
投票
@Jk1 的答案很好,但是 Mockito 还允许使用注释进行更简洁的注入:

@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too @Mock MyInterface myInterface

但是无论您使用哪种方法,注释都不会被处理(甚至您的 @Mock 也不会被处理),除非您以某种方式调用静态

MockitoAnnotation.initMocks()

 或使用 
@RunWith(MockitoJUnitRunner.class)
 注释类。


2
投票
@jk1 答案很完美,因为@igor Ganapolsky 问,为什么我们不能在这里使用 Mockito.mock ?我发布这个答案。

为此,我们为 myobj 提供了一种 setter 方法,并使用模拟对象设置 myobj 值。

class MyClass { MyInterface myObj; public void abc() { myObj.myMethodToBeVerified (new String("a"), new String("b")); } public void setMyObj(MyInterface obj) { this.myObj=obj; } }

在我们的测试类中,我们必须编写以下代码

class MyClassTest { MyClass myClass = new MyClass(); @Mock MyInterface myInterface; @test testAbc() { myclass.setMyObj(myInterface); //it is good to have in @before method myClass.abc(); verify(myInterface).myMethodToBeVerified(new String("a"), new String("b")); } }
    

0
投票
如果您期望 thisMethod() 执行,但它没有执行,也可能会抛出此异常。事实并非如此,因为它处于未满足的条件内。

例如,如果你有一些单元测试说验证 thisMethod() 被执行,但实际上,这并不是因为 varX 和 varY 不相等。

//method expected to be called. if( varX == varY){ thisMethod(); } //test Mockito.verify(foo).thisMethod();
    

0
投票
这是因为你的类没有被正确调用。 例如,

@模拟 类名 类名; …… verify(className).method(argument1, argument2); //实际代码

在这种情况下,没有为 junit 调用 className.class。 将其设为 =>

的代码

@模拟 类类名; …… 类名 类名 = mock(类名.class); //调用junit的className。 verify(className).method(argument1, argument2);

© www.soinside.com 2019 - 2024. All rights reserved.