使用 Dagger2 注入的 Espresso 测试
Espresso test with Dagger2 injection
我想在我的 Espresso 测试中注入由 dagger 创建的组件。
组件应该相同,所以没有必要覆盖 dagger 中的任何内容。
我有以下 class:
@RunWith(AndroidJUnit4.class)
public class AccountRepositoryTest {
@Inject
AccountRepository repository;
@Before
public void setUp() throws Exception {
new DaggerTestComponent().builder().build().inject(this);
}
}
由于我无法将 AccountRepositoryTest 添加到我的主要 DaggerComponent class,我在我的 androidTests 文件夹中创建了另一个组件 class:
@Singleton
@Component(modules = arrayOf(AppModule::class, DatabaseModule::class, RepositoryModule::class))
interface TestComponent: AppComponent {
fun inject(accountRepositoryTest: AccountRepositoryTest)
}
但是 dagger 从来没有从 TestComponent 接口生成 ComponentClass,当我编译代码时,我总是收到这个错误:
Error:(26, 7) error: cannot find symbol class DaggerTestComponent
如果我注释该行,我的代码会编译,所以我确信正是这个阻止了 dagger 生成 class.
所以我的问题是:如何使 dagger 从 androidTests 文件夹中定义的接口生成组件 class?
解决方案是将 dagger-compiler 添加到 androidTest 依赖项。
如果您使用的是科特林:
kaptAndroidTest "com.google.dagger:dagger-compiler:$daggerVersion"
如果您正在使用 java:
androidTestAnnotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"
我想在我的 Espresso 测试中注入由 dagger 创建的组件。
组件应该相同,所以没有必要覆盖 dagger 中的任何内容。
我有以下 class:
@RunWith(AndroidJUnit4.class)
public class AccountRepositoryTest {
@Inject
AccountRepository repository;
@Before
public void setUp() throws Exception {
new DaggerTestComponent().builder().build().inject(this);
}
}
由于我无法将 AccountRepositoryTest 添加到我的主要 DaggerComponent class,我在我的 androidTests 文件夹中创建了另一个组件 class:
@Singleton
@Component(modules = arrayOf(AppModule::class, DatabaseModule::class, RepositoryModule::class))
interface TestComponent: AppComponent {
fun inject(accountRepositoryTest: AccountRepositoryTest)
}
但是 dagger 从来没有从 TestComponent 接口生成 ComponentClass,当我编译代码时,我总是收到这个错误:
Error:(26, 7) error: cannot find symbol class DaggerTestComponent
如果我注释该行,我的代码会编译,所以我确信正是这个阻止了 dagger 生成 class.
所以我的问题是:如何使 dagger 从 androidTests 文件夹中定义的接口生成组件 class?
解决方案是将 dagger-compiler 添加到 androidTest 依赖项。
如果您使用的是科特林:
kaptAndroidTest "com.google.dagger:dagger-compiler:$daggerVersion"
如果您正在使用 java:
androidTestAnnotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"