使用自定义应用程序与InstrumentationTestCase

5
我有一个ActivityInstrumentationTestCase2测试用例(是InstrumentationTestCase的子类)。在运行我的测试用例时,我需要使用自定义的TestApplication对象来启动我的活动,因为这个TestApplication对象对于我的测试来说是必要的一些配置。
然而,我没有找到一种方法来自定义我的ActivityInstrumentationTestCase2测试用例以使用测试应用程序对象。有没有办法这样做?
2个回答

6

我不知道是否有更好的方法,但是我可以通过使用自定义的TestRunner来实现这个目标。

public class MyInstrumentationTestRunner extends InstrumentationTestRunner {

    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return new MyTestApplication(context);       
    }


}

我还需要修改测试项目的AndroidManifest.xml文件,以指定新的运行器:

<instrumentation android:name="com.mypackage.test.MyInstrumentationTestRunner" ... />

我不得不修改我的IDE以使用指定的测试运行程序。如果您从命令行运行,则需要执行以下操作:

adb shell am instrument -w com.mypackage/com.mypackage.test.MyInstrumentationTestRunner

4

应该是这样的

@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return Instrumentation.newApplication(YourAppClass.class, context);      
}

因为它正确地向包装器注入上下文。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接