我正在使用dagger2对我的一个用例(MVP架构,如果有关系的话)进行junit测试。问题是我有时想在我的junit测试用例中使用Dagger2注入。因此,我在DaggerMock库中查找了该库。我有一个我想为自己构建的依赖项,但它总是返回null。让我先向你展示我是如何设置dagger的。
这是一个单独的组件(尝试过子组件,但daggerMock对此不满意):AppComponent.java:
@Singleton
@Component(modules = {AppModule.class, NetworkModule.class, RepositoryModule.class, UseCaseModule.class, ActivityModule.class, PresenterModule.class})
public interface AppComponent {
void inject(NetworkSessionManager target);
void inject(SplashActivity target);
void inject(AuthenticationActivity target);
void inject(WelcomeActivity target);
void inject(LoginFragment target);
}其余的类使用@inject进行注释。如果你用@Inject注解这个类的构造函数,那就意味着你不必在上面的AppComponent接口中去关心它。
下面是我使用DaggerMock的测试用例:
@Rule
public final DaggerMockRule<AppComponent> rule = new DaggerMockRule<>(AppComponent.class, new AppModule(null),new RepositoryModule(),new NetworkModule(),new UseCaseModule());
StandardLoginInfo fakeLoginInfo;
TestObserver<Login> subscriber;
DoStandardLoginUsecase target_standardLoginUsecase;//this is what im trying to test so its real
@InjectFromComponent
UserDataRepository userDataRepository; //id like this to be a real instance also but it keeps showing as null
@Before
public void setUp() throws Exception {
target_standardLoginUsecase = new DoStandardLoginUsecase(userDataRepository); // this gets passed a null, why ?
subscriber = TestObserver.create();
}
//....
}如果我们看一下我定义的规则,我包含了appcomponent中的所有模块,所以我认为我有所有的依赖项可用。我把null传给了AppModule,因为它需要一个上下文,我觉得这没什么大不了的。
我认为@InjectFromComponent注解会给我想要的东西。我甚至尝试过@InjectFromComponent(DoStandardLoginUsecase.class),但这不起作用。我想把它放到安卓的AppComponent中,给我创建一个UserDataRepository对象。因为我使用的是DaggreMockRule中的所有模块,所以我想这样做不会很难吧?
怎样才能让dagger2构建一个真实的对象呢?
https://stackoverflow.com/questions/44486296
复制相似问题