Dagger2注射咖啡测试

我想在我的Espresso测试中注入由匕首创建的组件。

组件应该是一样的,所以,没有必要用匕首来压倒任何东西。

我有以下班级:

@RunWith(AndroidJUnit4.class) public class AccountRepositoryTest { @Inject AccountRepository repository; @Before public void setUp() throws Exception { new DaggerTestComponent().builder().build().inject(this); } } 

由于我不能将AccountRepositoryTest添加到我的主要DaggerComponent类,所以我在我的androidTests文件夹中创建了另一个组件类:

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

但是匕首永远不会从TestComponent接口生成ComponentClass,当我编译代码时,我总是收到这个错误:

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

如果我评论这行,我的代码会被编译,所以我确信这只是防止匕首生成类。

所以我的问题是:如何使匕首从androidTests文件夹中定义的接口生成组件类?

解决方案是将匕首编译器添加到androidTest依赖项。

如果您正在使用kotlin:

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

如果您使用的是java:

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