在InstrumentationTestCase中进行模拟

时间:2015-07-10 12:48:03

标签: android mocking mockito android-instrumentation

我尝试在我的仪器测试中模拟一个方法,但它失败了,我正在寻找解决方案来解决它。

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);

    }

崩溃发生在以下一行:

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

我得到了以下错误:

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.

1 个答案:

答案 0 :(得分:1)

您需要模拟每个方法调用:getInstrumentation().getContext().getApplicationContext();

示例:

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);