2

MyApplicationclass (extends Application),当它启动时,将启动一个服务来检查一个SharedPreference值。如果值为false,则初始化一些数据。

出于测试目的,我想将其修改SharedPreferencetrue不会发生数据初始化。但是,当我这样做时,会发生竞争条件并MyApplication.onCreate()在我有机会修改首选项之前调用它。

如何在MyApplication.onCreate()调用之前修改首选项?这样的事情甚至可能吗?

我的应用程序.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 (在 src/androidTest 风格中)

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

}
4

0 回答 0