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.
I have some init code that I don't want called during instrumentation tests.
onCreate() - called before the first components of the application starts. onLowMemory() - called when the Android system requests that the application cleans up memory.
ActivityScenario provides APIs to start and drive an Activity's lifecycle state for testing. It works with arbitrary activities and works consistently across different versions of the Android framework. The ActivityScenario API uses Lifecycle.
Instrumented tests are tests that run on physical devices and emulators, and they can take advantage of the Android framework APIs and supporting APIs, such as AndroidX Test.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With