使用不同的Application类测试Android活动

20

我正在寻找一种使用JUnit4和ActivityTestRule测试活动的方法,但使用不同的应用程序类(例如模拟或继承)。我能够在库项目中使用清单合并和androidTest / AndroidManifest.xml中的工具:replace =“android:name”在应用标签上来实现这一点。但是,对于应用程序,这种方法不起作用。

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

1个回答

42

你可以通过创建自己的Runner并覆盖newApplication()方法,以自定义应用程序类来创建AndroidJUnitRunner的子类。

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);
}
}

请确保按照以下方式使用新的Runner更新您的build.gradle文件:

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


3
感谢您指出这一点:testInstrumentationRunner "com.mypackage.name.path.CustomTestRunner"。许多其他教程都没有提到这一点。 - Xi Wei
4
如果你正在通过Android Studio运行测试,可能需要更新你的“特定测试运行器(Specific instrumentation runner)”在Run/Debug Configuration中指向你的CustomTestRunner的相应位置。 - Max
4
我能否指定一些测试使用应用程序类A,而其他测试使用类B?比如我想让一些测试使用带有依赖注入的应用程序,而另一些则不使用。 - Sreekanth
@Sreekanth,这可以通过自定义测试规则来完成。请参阅此评论https://dev59.com/xeo6XIcBkEYKwwoYGwMZ#36778841。请注意,它仍然会在某种程度上运行您的应用程序,但然后会根据每个测试执行覆盖的App类。 - Den Drobiazko
我无法扩展AndroidJUnitRunner。我应该把自定义运行器放在哪里? - Cafer Mert Ceyhan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接