【问题标题】:DaggerMock - How to get dagger to provide object in a test caseDaggerMock - 如何让匕首在测试用例中提供对象
【发布时间】:2017-11-13 03:41:57
【问题描述】:

我正在使用 dagger2 对我拥有的用例(MVP 架构,如果这很重要)进行 junit 测试。 问题是我有时想在我的 junit 测试用例中使用 Dagger2 注入。 所以我为此查看了DaggerMock 库。我有一定的依赖,我想为我构建,但它一直返回 null。 让我先告诉你我是如何设置匕首的。

它是一个组件(尝试了子组件,但 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 android 为我构建一个 UserDataRepository 对象。由于我使用的是 DaggreMockRule 中的所有模块,我认为这样做不会很困难?

我怎样才能让 dagger2 为我打造一个真实的对象?

【问题讨论】:

    标签: android junit mockito dagger-2 daggermock


    【解决方案1】:

    这里的诀窍是,无论你想注入什么,都必须直接暴露在组件中。因此,例如让您的组件像这样:

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

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多