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 :

Mockito.doReturn(this.getContext().getAssets()).when(keyboard).getAssets();

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>(){
    @Override
    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:

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 the method with the original parameters in Mockito?

Thanks in advance

Solution

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