使用不同的Application类测试Android Activity

Fab*_*ian 10 android android-testing android-espresso

我正在寻找一种方法来测试一个使用JUnit4和ActivityTestRule的Activity,但是使用不同的应用程序类(例如模拟或继承).我能够使用清单合并和工具来获取这个项目:在androidTest/AndroidManifest.xml中的application标签上替换="android:name".然而,这不适用于应用程序.

有什么想法可以做到这一点?

Be_*_*ive 28

您可以AndroidJUnitRunner使用自己的运行器对其进行子类化,并newApplication()使用自定义应用程序类覆盖它.

public class CustomTestRunner extends AndroidJUnitRunner {

@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return super.newApplication(cl, CustomTestApplication.class.getName(), context);
}
}
Run Code Online (Sandbox Code Playgroud)

确保使用新的运行器更新build.gradle,如下所示:

testInstrumentationRunner "com.mypackage.name.path.CustomTestRunner"

  • 感谢您指出:testInstrumentationRunner"com.mypackage.name.path.CustomTestRunner".许多其他教程都没有这样做. (3认同)
  • 此外,如果您在Android Studio中运行测试,则可能需要在运行/调试配置中更新"特定仪器运行器"以指向您的CustomTestRunner等效项. (3认同)
  • 有没有一种方法可以指定某些测试应将A用作应用程序类,而其他测试则将B用作应用程序类?就像我希望某些测试将Application与依赖项注入一起使用,而另一些则没有。 (3认同)