我正在用dagger2对一个用例(如果重要的话,是mvp架构)进行junit测试。
问题是有时我想在JUnit测试用例中使用Dagger2注入。
所以我查了一下图书馆。我有一个依赖关系,我想为我建立,但它一直返回空。
让我先告诉你我是怎么设置匕首的。
它是一个单一的组件(尝试过的子组件,但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注释。如果你用@injecttheclassconstructor进行注释,那么它意味着你不必
在上面的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中的所有模块,所以我认为我拥有所有可用的依赖项。
我将空值传递给appmodule,因为它需要一个上下文,我认为这没什么大不了的。
我认为@InjectFromComponent注释会给我想要的东西。我甚至试过@InjectFromComponent(DoStandardLoginUsecase.class),但那不起作用。我希望它进入appcomponent安卓系统
为我生成一个userdatarepository对象。既然我使用了daggeremockrule中的所有模块,我想这样做不会很困难吧?
我怎样才能得到匕首2来建造一个真正的物体?

最佳答案

这里的诀窍是,您要注入的任何内容都必须直接暴露在组件中。例如,您的组件如下:

@Singleton
@Component(modules = {AppModule.class, TestNetworkModule.class, RepositoryModule.class, ActivityModule.class})
public interface TestAppComponent {

    void inject(LoginFragment target);
    void inject(SignUpFragment target);

    MockWebServer server();
    UserDataRepository userDataRepo(); //these two can be injected because they are directly exposed (still put them in your module as usual. this just directly exposes them so daggermock can use them)
}

10-07 19:23
查看更多