ActivityTestRule - how to call code before Application's onCreate

徘徊边缘 提交于 2019-11-30 11:42:52

Application onCreate() is called after Instrumentation onCreate(). For this case you need to implement a custom test runner which will subclass AndroidJUnitRunner and will override the callApplicationOnCreate() with your custom setup.

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

Make sure to update your defaultConfig in the build.gradle to use new testInstrumentationRunner like this:

testInstrumentationRunner "com.myapp.MyCustomTestRunner"

If you are looking to run some code before Activity onCreate(), subclass ActivityTestRule with your own implementation of beforeActivityLaunched()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!