单元测试
不要使用 Dagger 进行单元测试
要使用 @Inject 带注释的构造函数测试类,您不需要匕首。而是使用带有假或模拟依赖项的构造函数创建一个实例。
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));
}
}
功能/集成/端到端测试
功能/集成/端到端测试通常使用生产
应用程序,但用 fakes[^fakes-not-mocks] 代替持久性,
后端和身份验证系统,将应用程序的其余部分留给
正常运行。这种方法适合拥有一个(或者可能是一个
小有限数量)的测试配置,其中测试
配置替换了 prod 配置中的一些绑定。
你有两个选择:
选项 1:通过子类化模块覆盖绑定
@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。