Java – Mockito – Overrides methods that take raw parameters

Mockito – Overrides methods that take raw parameters… here is a solution to the problem.

Mockito – Overrides methods that take raw parameters

I have a class that is a subclass of Context. I’m doing unit tests on another class that depends on this class, so I mocked it. However, I need some way to act as their original behavior, so I’ll “unmock” them.

One of them is getAssets() so I wrote this and it works fine :


The keyboard is a simulated instance of the above class.

Since this method does not accept any parameters, it is very simple to override it.

I also need to override Context.getString(int). This parameter makes things difficult, and it’s the original parameter that makes things even more difficult.

I took this advice and another and tried to write this code:

Mockito.when(keyboard.getString(Mockito.anyInt())).thenAnswer(new Answer<String>(){
    public String answer(InvocationOnMock invocation) throws Throwable
         Integer arg = (Integer)invocation.getArguments()[0];
         return OuterClass.this.getContext().getString(arg.intValue());

Compiles and executes with the following exception:

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:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

at android.content.Context.getString(
at [...]
at android.test.AndroidTestRunner.runTest(
at android.test.AndroidTestRunner.runTest(
at android.test.InstrumentationTestRunner.onStart(

So the main question is how to override the method with the original parameters in Mockito?

Thanks in advance


You can’t stub getString because it’s final. Mockito cannot stub the final method. Just keep its stub and you’ll get its original implementation. That’s what you want, right?

Related Problems and Solutions