Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActivityTestRule - how to call code before Application's onCreate

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.

like image 789
smdremedy Avatar asked May 05 '15 12:05

smdremedy


People also ask

What is it called when an application is onCreate?

onCreate() - called before the first components of the application starts. onLowMemory() - called when the Android system requests that the application cleans up memory.

What is an Activity scenario?

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.

What is instrumented unit test?

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.


1 Answers

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

like image 168
Be_Negative Avatar answered Sep 18 '22 16:09

Be_Negative