I am trying to mock spring's applicationContext.getBean(String, Class) method in below manner -
when(applicationContext.getBean(Mockito.anyString(), Mockito.eq(SomeClass.class))).thenAnswer(
new Answer<SomeClass>() {
@Override
public SomeClass answer(InvocationOnMock invocation) throws Throwable {
// doing some stuff and returning the object of SomeClass
}
});
The scenario is that, the applicationContext.getBean method will be called a number of times, each time a with different strings but the same class (SomeClass.class).
The problem I am getting here is that the answer is getting invoked for the very first invocation of getBean method. With each subsequent invocation of getBean I am getting below exception -
******org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));******
Any idea, if I am missing something ?
@Kshitij
I have faced same issue in my previous project. I came across this below doc: http://static.javadoc.io/org.mockito/mockito-core/2.16.0/org/mockito/Mockito.html#resetting_mocks
Under section 17 it is explained how to use reset()
Example: Let's say we have EvenOddService which finds whether number is even or odd then Test case with reset() will look like:
when(evenOddService.isEven(20)).thenReturn(true);
Assert.assertEquals(evenOddController.isEven(20), true);
//allows to reuse the mock
reset(evenOddService);
Assert.assertEquals(evenOddController.isEven(20), true);
Hope this helps :).
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