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

use*_*886 7 java android integration-testing dagger-2

Dagger 2 文档建议使用interfacefor ProductionComponent提供不同的测试和生产配置TestComponent,如下所示:

@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();
}
Run Code Online (Sandbox Code Playgroud)

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

public class MyApp extends Application {
    private ProductionComponent component;

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

        component = ProductionComponent.builder()
                .serverModule(new ServerModule())
                .build();
    }
}
Run Code Online (Sandbox Code Playgroud)

通常,什么是最好的使用方式DaggerTestComponent.builder()而不是ProductionComponent.builder()Android集成测试?

我不确定如何使用假货; 我应该在一个新的活动/androidTest,其extends MyApp?或者我应该通过在新DaggerTestComponentMyApp使用的getter/setter,当我安装我的测试?

myo*_*jin 0

将robolectricMockito一起使用怎么样?

您可以使用 @Test 编写 JUnit 测试代码,而无需 AndroidTest。我认为你用 Mockito 做了测试匕首应用程序。

参考这里

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