使用不同的应用程序类测试 Android Activity [英] Test Android Activity with different Application class
问题描述
我正在寻找一种使用 JUnit4 和 ActivityTestRule 测试活动的方法,但使用不同的应用程序类(例如模拟或继承).我能够使用清单合并和 tools:replace="android:name" 在 androidTest/AndroidManifest.xml 中的应用程序标记上为库项目获取此信息.但是,这不适用于应用程序.
I´m looking for a way to test an Activity with JUnit4 and the ActivityTestRule, but with a different application class (e.g. mocked or inherited). I was able to get this for library projects using the manifest merge and tools:replace="android:name" on the application tag in the androidTest/AndroidManifest.xml. This however does not work for applications.
知道如何做到这一点吗?
Any ideas how this can be done?
推荐答案
您可以使用您自己的运行程序对 AndroidJUnitRunner
进行子类化,并使用您的自定义应用程序类覆盖 newApplication()
.
You can subclass the AndroidJUnitRunner
with your own runner and override newApplication()
with your custom application 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,如下所示:
Make sure to update your build.gradle with the new runner like this:
testInstrumentationRunner "com.mypackage.name.path.CustomTestRunner"
这篇关于使用不同的应用程序类测试 Android Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!