安卓测试 : use Dagger2 + Gradle

标签 android testing gradle dagger-2

我了解 Dagger2 的工作原理,

我知道它允许轻松交换依赖关系,因此我们可以使用模拟进行测试。

重点是我不确定我是否理解我应该如何为测试和调试/生产提供不同的 Dagger2 组件实现。

我是否需要创建 2 个 Gradle productFlavors(例如“Production”/“Test”) 那将包含 2 个不同的组件定义?

或者我可以指定我想使用模拟组件进行测试编译,使用非模拟组件进行非测试构建吗?

我很困惑,请澄清一下就好了!

非常感谢!

最佳答案

单元测试

Don’t use Dagger for unit testing

要用@Inject 注释的构造函数测试类,您不需要 Dagger 。而是使用具有虚假或模拟依赖项的构造函数创建一个实例。

final class ThingDoer {
  private final ThingGetter getter;
  private final ThingPutter putter;

  @Inject ThingDoer(ThingGetter getter, ThingPutter putter) {
    this.getter = getter;
    this.putter = putter;
  }

  String doTheThing(int howManyTimes) { /* … */ }
}

public class ThingDoerTest {
  @Test
  public void testDoTheThing() {
    ThingDoer doer = new ThingDoer(fakeGetter, fakePutter);
    assertEquals("done", doer.doTheThing(5));
  }
}

功能/集成/端到端测试

Functional/integration/end-to-end tests typically use the production application, but substitute fakes[^fakes-not-mocks] for persistence, backends, and auth systems, leaving the rest of the application to operate normally. That approach lends itself to having one (or maybe a small finite number) of test configurations, where the test configuration replaces some of the bindings in the prod configuration.

这里有两个选择:

选项 1:通过子类化模块覆盖绑定(bind)

    @Component(modules = {AuthModule.class, /* … */})
    interface MyApplicationComponent { /* … */ }

    @Module
    class AuthModule {
      @Provides AuthManager authManager(AuthManagerImpl impl) {
        return impl;
      }
    }

    class FakeAuthModule extends AuthModule {
      @Override
      AuthManager authManager(AuthManagerImpl impl) {
        return new FakeAuthManager();
      }
    }

    MyApplicationComponent testingComponent = DaggerMyApplicationComponent.builder()
        .authModule(new FakeAuthModule())
        .build();

选项 2:单独的组件配置

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

official documentation testing page 中了解更多信息.

关于安卓测试 : use Dagger2 + Gradle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35912915/

相关文章:

java - 如何在框架布局中设置位置?

java - Android:如何判断我是否有权限打开目录?

android - 测试Android应用程序时要记住的要点

java - Tess4J NoClassDefFoundError

android - 将 Android Studio Gradle 升级到 6.1.1 会破坏 Greendao3GradlePlugin

android - 如何在单独的类中使用自定义 ArrayAdapter?

android - Google-play-services_lib 无法解析目标“android-9”

java - JUnit 如何测试 ParseException

ruby-on-rails-3 - Rails 3 - .Nil?重定向不起作用

java - 将本地注释处理器项目集成到 gradle 构建中