Android 通过InstrumentationTestCase使用自定义应用程序

Android 通过InstrumentationTestCase使用自定义应用程序,android,testing,Android,Testing,我有一个ActivityInstrumentationTestCase2(它是InstrumentationTestCase的一个子类)。当运行我的测试用例时,我需要使用一个定制的TestApplication对象启动我的活动,因为这个TestApplication对象有一些测试所需的配置 但是,我看不到定制ActivityInstrumentationTestCase2测试用例以使用测试应用程序对象的方法。有什么方法可以做到这一点吗?我不知道是否有更好的方法,但我可以通过使用定制的TestRu

我有一个ActivityInstrumentationTestCase2(它是InstrumentationTestCase的一个子类)。当运行我的测试用例时,我需要使用一个定制的TestApplication对象启动我的活动,因为这个TestApplication对象有一些测试所需的配置


但是,我看不到定制ActivityInstrumentationTestCase2测试用例以使用测试应用程序对象的方法。有什么方法可以做到这一点吗?

我不知道是否有更好的方法,但我可以通过使用定制的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" ... />
应该是

@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return Instrumentation.newApplication(YourAppClass.class, context);      
}
因为它正确地将上下文注入包装器

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