Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

后端 未结 4 1857
旧时难觅i
旧时难觅i 2020-12-08 06:20

I have interface

Interface MyInterface {
  myMethodToBeVerified (String, String);
}

And implementation of interface is

clas         


        
相关标签:
4条回答
  • 2020-12-08 07:00

    Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.

    0 讨论(0)
  • 2020-12-08 07:03

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

    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"));
    }
    
    0 讨论(0)
  • 2020-12-08 07:03

    @jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.

    For that we have provide one setter method for myobj and set the myobj value with mocked object.

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

    In our Test class, we have to write below code

    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 讨论(0)
  • 2020-12-08 07:07

    @Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:

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

    But regardless of which method you use, the annotations are not being processed (not even your @Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with @RunWith(MockitoJUnitRunner.class).

    0 讨论(0)
提交回复
热议问题