ActivityTestRule - 如何在应用程序创建之前调用代码



我正在使用ActivityTestrule使用Espresso 2.1,我正在寻找一种在我的应用程序中的onCreate()之前设置一些静态标志的方法。

我有一些在仪器测试中我不想调用的初始代码。

应用程序 onCreate()在仪器onCreate()之后调用。在这种情况下,您需要实现一个自定义测试跑者,该跑步者将通过您的自定义设置来覆盖AndroidJunitrunner,并将覆盖CallapplicationOncreate()。

public class MyCustomTestRunner extends AndroidJUnitRunner {
@Override
public void callApplicationOnCreate(Application app) {
    InstrumentationRegistry.getTargetContext().getSharedPreferences().doMyStuff();
    super.callApplicationOnCreate(app);
}
}

确保在build.gradle中更新您的defaultConfig以使用新的TestInstrumentationRunner:

testInstrumentationRunner "com.myapp.MyCustomTestRunner"

如果您想在活动之前运行一些代码 onCreate(),则使用您自己的beforeActivityLaunched()

的实现,子类活动图。

最新更新