Dagger 2文档建议使用接口来为测试和生产提供不同的配置,其中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();
}
假设我们有一个使用
ProductionComponent
的 Android 活动 (MyApp
):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()
更好的方式是什么?
我不确定如何使用伪造对象;我应该在/androidTest
中创建一个新的活动,并将其扩展为MyApp
吗?还是当我设置我的测试时,应该通过getter/setter将一个新的DaggerTestComponent
传递给MyApp
?