使用不同的Application类测试Android Activity [英] Test Android Activity with different Application class

查看:92
本文介绍了使用不同的Application类测试Android Activity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用JUnit4和ActivityTestRule测试Activity的方法,但是要使用不同的应用程序类(例如,模拟的或继承的).我可以使用清单合并和androidTest/AndroidManifest.xml中应用程序标记上的tools:replace ="android:name"在图书馆项目中使用此功能.但是,这不适用于应用程序.

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"

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

这篇关于使用不同的Application类测试Android Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆