I have interface
Interface MyInterface { myMethodToBeVerified (String, String); }
And implementation of interface is
class MyClassToBeTested implements MyInterface { myMethodToBeVerified(String, String) { ……. } }
I have another class
class MyClass { MyInterface myObj = new MyClassToBeTested(); public void abc(){ myObj.myMethodToBeVerified (new String(“a”), new String(“b”)); } }
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”)); } }
But I am getting mockito wanted but not invoked, Actually there were zero interactions with this mock at verify call.
can anyone suggest some solutions.
@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.
We can use the @MockBean to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context. If no bean of the same type is defined, a new one will be added.
Using the verify() Method Mockito provides us with a verify() method that lets us verify whether the mock void method is being called or not. It lets us check the number of methods invocations. So, if the method invocation returns to be zero, we would know that our mock method is not being called.
Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.
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")); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With