I have a class which is subclass of Context
. I'm unit-testing another class which have dependency to this class, and therefore I've mocked it. However, I need some methods to act as their original behavior, so I'm going to "unmock" them.
One of them is getAssets()
so I wrote this and it works correctly:
Mockito.doReturn(this.getContext().getAssets()).when(keyboard).getAssets();
keyboard
is the mocked instance of the class mentioned.
Since this method takes no parameters, overriding it was pretty simple.
I also need to override Context.getString(int)
too. The parameter makes things difficult and it being a primitive, makes even more difficult.
I took this advice and another one, and tried writing this code:
Mockito.when(keyboard.getString(Mockito.anyInt())).thenAnswer(new Answer<String>(){
@Override
public String answer(InvocationOnMock invocation) throws Throwable
Integer arg = (Integer)invocation.getArguments()[0];
return OuterClass.this.getContext().getString(arg.intValue());
}
});
This compiled and executed, but gave the following exception:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at [...] <The code above>
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"));
For more info see javadoc for Matchers class.
at android.content.Context.getString(Context.java:282)
at [...]
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:545)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)
So the main question is How to override methods in Mockito, which have primitive parameters?
Thanks in advance