使用InstrumentationTestCase的自定义应用程序

emm*_*mby 5 testing android

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

但是,我没有看到自定义ActivityInstrumentationTestCase2测试用例以使用测试Application对象的方法.有办法吗?

emm*_*mby 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);       
    }


}
Run Code Online (Sandbox Code Playgroud)

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

<instrumentation android:name="com.mypackage.test.MyInstrumentationTestRunner" ... />
Run Code Online (Sandbox Code Playgroud)

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

adb shell am instrument -w com.mypackage/com.mypackage.test.MyInstrumentationTestRunner
Run Code Online (Sandbox Code Playgroud)