使用 AndroidJunitRunner 和 Dagger2 模拟依赖错误

Mocking dependency error with AndroidJunitRunner and Dagger2

我正在尝试像 https://artemzin.com/blog/how-to-mock-dependencies-in-unit-integration-and-functional-tests-dagger-robolectric-instrumentation/

中建议的那样模拟依赖项

不幸的是,当我 运行 我的 AndroidJunit4 测试时,我无法克服以下错误:

测试 运行ning 失败:无法找到以下的检测信息:ComponentInfo{com.fisincorporated.aviationweather.test/android.support.test.runner.AndroidJUnitRunner}

我尝试了各种不依赖于 Android Studio 版本的 SO 解决方案,但没有成功

我的应用级别 gradle 代码段是:

android {
   ...
defaultConfig {
     ...
    testInstrumentationRunner "com.fisincorporated.aviationweather.app.OverrideApplicationTestRunner"
}
...
}

我的 OverrideApplicationTestRunner 是:

public class OverrideApplicationTestRunner extends AndroidJUnitRunner {
@Override
@NonNull
public Application newApplication(@NonNull ClassLoader cl,
                                  @NonNull String className,
                                  @NonNull Context context)
        throws InstantiationException,
        IllegalAccessException,
        ClassNotFoundException {
    return Instrumentation.newApplication(WeatherApplicationTest.class, context);
}
}

WeatherApplicationTest

public class WeatherApplicationTest extends WeatherApplication {

@Override
protected void createDaggerInjections() {
    component = DaggerDiComponent.builder()
            .appModule(new AppModule(this) {
                @Override
                public String providesAppSharedPreferencesName() {
                    return "SHARED_AIRPORT_FUNCTIONAL_TEST";
                }

                public Retrofit provideAppRetrofit() {
                    return new AppRetrofit(new MockInterceptor()).getRetrofit();
                }
            })
            .build();
    component.inject(this);
}
}

和 AirportWeatherActivityTest

@RunWith(AndroidJUnit4.class)
public class AirportWeatherActivityTest {

    @Rule
    public ActivityTestRule<AirportWeatherActivity> mActivityRule =
            new ActivityTestRule<>(AirportWeatherActivity.class, true, false);

    @Test
    public void someTest() {
        Context targetContext = InstrumentationRegistry.getTargetContext();
        Intent intent = new Intent(targetContext, AirportWeatherActivity.class);

        mActivityRule.launchActivity(intent);
        assertThat(mActivityRule.getActivity().airportWeatherViewModel.airportWeatherList.size(),is(0));

    }
}

androidTest目录结构如下:

我发现如果我 运行 下面的测试,它就可以工作,即我看到 WeatherApplicationTest 正在执行。所以看起来 testInstrumentationRunner 正在寻找我的 OverrideApplicationTestRunner。

@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
    // Context of the app under test.
    Context appContext = InstrumentationRegistry.getTargetContext();

    assertEquals("com.fisincorporated.aviationweather", appContext.getPackageName());
}
}

那么是使用ActivityTestRule引起的问题吗?

P.S。我忘了说我是测试新手,所以如果我遗漏了一些明显的东西,我深表歉意。

将 android 插件版本切换到 2.2.3,然后再切换回 2.3.0,清理项目和构建解决了这个问题。