0

I try to mock a method in my instrumentation test but it fails and I am looking for a solution to solve it.

public class MyTest extends InstrumentationTestCase {

    private Context mAppCtx;

    @Override
    public void setUp() throws Exception {
        super.setUp();

        Context context = mock(Context.class);

        mAppCtx = getInstrumentation().getContext().getApplicationContext();                

        when(mAppCtx.createPackageContext(PACKAGE_NAME, 0)).thenReturn(context);

    }

A crash happens on the following line:

when(mAppCtx.createPackageContext(PACKAGE_NAME, 0)).thenReturn(context);

And I got following error:

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
It is a limitation of the mock engine.
galath
  • 5,717
  • 10
  • 29
  • 41
Ali
  • 9,800
  • 19
  • 72
  • 152

1 Answers1

1

You need to mock each method invocation of: getInstrumentation().getContext().getApplicationContext();

Example:

Instrumentation inst = mock(Instrumentation.class);
Context instContext = mock(Context.class);
ApplicationContext mAppCtx= mock(ApplicationContext.class);
when(getInstrumentation()).thenReturn(inst);
when(inst.getContext()).thenReturn(instContext);
when(instContext.getApplicationContext()).thenReturn(mAppCtx);
when(mAppCtx.createPackageContext(PACKAGE_NAME, 0)).thenReturn(context);
Armin
  • 373
  • 1
  • 9
  • How if I mock two contexts and use them instead of mocking everything? `when(fakeContext.createPackageContext(PACKAGE_NAME, 0)).thenReturn(mockContext);` – Ali Jul 10 '15 at 18:39
  • It depends on what you are trying to test. You use "when" to mock out functions that you don't want to test in your System Under Test (SUT). If it is directly used in your SUT, then you must mock all of the calls leading up to getApplicationContext to be able to mock getApplicationContext. – Armin Jul 10 '15 at 19:25