ActivityTestRule - how to call code before Application's onCreate

前端 未结 1 597
一向
一向 2021-01-01 22:32

I am using Espresso 2.1 with ActivityTestRule, and I am looking for a way to set some static flags before onCreate() in my application will be called.

相关标签:
1条回答
  • 2021-01-01 23:05

    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()

    0 讨论(0)
提交回复
热议问题