gpt4 book ai didi

android - ActivityTestRule - 如何在应用程序的 onCreate 之前调用代码

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:20:37 27 4
gpt4 key购买 nike

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

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

最佳答案

Application onCreate() 在 Instrumentation 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"

如果您希望在 Activity onCreate() 之前运行一些代码,请使用您自己的 beforeActivityLaunched() 实现子类 ActivityTestRule。

关于android - ActivityTestRule - 如何在应用程序的 onCreate 之前调用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052601/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com