在 Android 中使用单独的组件配置使用 Dagger 2 进行测试

Testing with Dagger 2 using separate component configurations in Android

用于测试和生产的 Dagger 2 documentation suggests providing different configurations 使用 interface 作为 ProductionComponentTestComponent,如下:

@Component(modules = {
  OAuthModule.class, // real auth
  FooServiceModule.class, // real backend
  OtherApplicationModule.class,
  /* … */ })
interface ProductionComponent {
  Server server();
}

@Component(modules = {
  FakeAuthModule.class, // fake auth
  FakeFooServiceModule.class, // fake backend
  OtherApplicationModule.class,
  /* … */})
interface TestComponent extends ProductionComponent {
  FakeAuthManager fakeAuthManager();
  FakeFooService fakeFooService();
}

假设我们有一个 Android activity (MyApp),它使用 ProductionComponent:

public class MyApp extends Application {
    private ProductionComponent component;

    @Override public void onCreate() {
        super.onCreate();

        component = ProductionComponent.builder()
                .serverModule(new ServerModule())
                .build();
    }
}

一般来说,在 Android 集成测试中使用 DaggerTestComponent.builder() 而不是 ProductionComponent.builder() 的最佳方法是什么?

我不确定如何使用假货;我应该在 extends MyApp 中的 /androidTest 中创建一个新的 activity 吗?或者我应该在设置测试时使用 getter/setter 将新的 DaggerTestComponent 传递到 MyApp 中吗?

使用 robolectric with Mockito 怎么样?

您可以使用@Test 制作JUnit 测试代码而无需使用AndroidTest。 我想你用 Mockito 制作测试匕首应用程序。

此处引用

http://alexzh.com/tutorials/android-testing-mockito-robolectric/ http://sdudzin.blogspot.kr/2011/01/easy-unit-testing-for-android.html