【问题标题】:Test Android Activity with different Application class使用不同的应用程序类测试 Android Activity
【发布时间】:2015-11-27 14:03:37
【问题描述】:

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

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

【问题讨论】:

    标签: android android-testing android-espresso


    【解决方案1】:

    您可以使用自己的运行器子类化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);
    }
    }
    

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

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

    【讨论】:

    • 感谢您指出这一点:testInstrumentationRunner "com.mypackage.name.path.CustomTestRunner"。许多其他教程都没有这样做。
    • 另外,如果您在 Android Studio 之外运行测试,您可能需要在运行/调试配置中更新您的 Specific instrumentation runner 以指向您的 CustomTestRunner 等效项。
    • 有没有办法可以指定一些测试应该使用 A 作为应用程序类而其他使用 B ?就像我想要一些测试使用带有依赖注入的应用程序而其他一些没有。
    • @Sreekanth 这可以通过自定义测试规则来完成。请参阅此评论stackoverflow.com/a/36778841/2957893。请注意,它仍然会以某种方式运行您的应用程序,但随后会在每个测试中执行 overridenn App 类
    • 我无法扩展 AndroidJUnitRunner。我可以把自定义跑步者放在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多