MyApplication
class (extends Application
), when it starts up, will launch a service to check a SharedPreference
value. If the value is false
, then some data gets initialized.
For testing purposes, I would like to modify this SharedPreference
to be true
so the data initialization does not happen. However when I do this, a race condition happens and the MyApplication.onCreate()
is called before I have a chance to modify the preference.
How can I modify the preference before MyApplication.onCreate()
is called? Is something like this even possible?
MyApplication.java
public class MyApplication extends Application {
public static AppComponent component;
public MyApplication() {
}
@Override
public void onCreate() {
injectDependencies();
super.onCreate();
initializeDatabase();
}
private void injectDependencies() {
if (component == null)
component = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
component.inject(this);
}
@VisibleForTesting
public static void setComponent(AppComponent component) {
MyApplication.component = component;
}
private void initializeDatabase() {
Intent intent = DataInitializationService.createIntent(this, null);
startService(intent);
}
}
SearchFragmentTest.java (in src/androidTest flavor)
public class SearchScreenFragmentTest {
@Rule
public ActivityTestRule activityRule = new ActivityTestRule<>(
SearchActivity.class,
true, // initialTouchMode
false); // launchActivity. False to set intent per method
public SearchScreenFragmentTest() {
}
@Before
public void setUp() throws Exception {
//gets run AFTER `MyApplication.onCreate()`. I want this to be called BEFORE.
new TestUtils.TestDataInitter(InstrumentationRegistry.getTargetContext())
.clearPrefs(true)
.acceptIntro(true)
.initDatabaseFake(true)
.init();
}
@After
public void tearDown() throws Exception {
new TestUtils.TestDataInitter(InstrumentationRegistry.getTargetContext())
.clearPrefs(true)
.acceptIntro(true)
.initDatabaseFake(false)
.init();
}
}