简体   繁体   English

注射Dagger2进行浓咖啡测试

[英]Espresso test with Dagger2 injection

I want to inject my components that are created by dagger in my Espresso tests. 我想注入我的Espresso测试中由dagger创建的组件。

The components should be the same, so, that are no necessity of overriding anything from dagger. 组件应该相同,因此不必覆盖匕首中的任何内容。

I have the following class: 我有以下课程:

@RunWith(AndroidJUnit4.class)
public class AccountRepositoryTest {
    @Inject
    AccountRepository repository;

    @Before
    public void setUp() throws Exception {
        new DaggerTestComponent().builder().build().inject(this);
    }
}

Since I can't add AccountRepositoryTest to my main DaggerComponent class, I created another component class in my androidTests folder: 由于无法将AccountRepositoryTest添加到我的主要DaggerComponent类中,因此我在androidTests文件夹中创建了另一个组件类:

@Singleton
@Component(modules = arrayOf(AppModule::class, DatabaseModule::class, RepositoryModule::class))
interface TestComponent: AppComponent {
     fun inject(accountRepositoryTest: AccountRepositoryTest)
}

But dagger never generates the ComponentClass from TestComponent interface, when I compile the code, I always receive this error: 但是匕首从不从TestComponent接口生成ComponentClass,当我编译代码时,我总是会收到此错误:

Error:(26, 7) error: cannot find symbol class DaggerTestComponent

If I comment the line, my code compiles, so I'm sure that it is just this that is preventing dagger from generating the class. 如果我注释掉这行代码,我的代码就会编译,因此我确定正是这种原因阻止了匕首生成类。

So my question is: how do make dagger generate a component class from an interface defined in androidTests folder? 所以我的问题是:如何使dagger从androidTests文件夹中定义的接口生成组件类?

The solution was to add dagger-compiler to androidTest dependencies. 解决方案是将dagger-compiler添加到androidTest依赖项。

If you are using kotlin: 如果您使用的是Kotlin:

kaptAndroidTest "com.google.dagger:dagger-compiler:$daggerVersion"

If you are using java: 如果您使用的是Java:

androidTestAnnotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM