使用不同的应用程序 class 测试 Android Activity

Test Android Activity with different Application class

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

知道如何做到这一点吗?

您可以将 class AndroidJUnitRunner 替换为您自己的运行程序,并使用您的自定义应用程序覆盖 newApplication() class。

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"