我正在尝试使用Dagger Hilt和Robolectric进行测试:
@RunWith(RobolectricTestRunner::class)
@UninstallModules(LevelModule::class, AppModule::class)
@Config(sdk = [16, 28], application = HiltTestApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
@HiltAndroidTest
class LevelFragmentTest {
@get:Rule
var rule = HiltAndroidRule(this)
@Test
fun testShowGameOverWhenTapAMine() {
launchActivity<GameActivity>().onActivity { activity ->
ShadowLooper.runUiThreadTasks()
...
}
}
测试失败是因为在GameActivity.onCreate
中,所有带有@inject注解的GameActivity字段均为空。
GameActivity是:
@AndroidEntryPoint
class GameActivity : AppCompatActivity()
这些模块包括:
@Module
@InstallIn(ActivityComponent::class)
open class LevelModule { ... }
@Module
@InstallIn(ActivityComponent::class)
class TestLevelModule {
@Module
@InstallIn(ApplicationComponent::class)
class AppModule() { ... }
@Module
@InstallIn(ApplicationComponent::class)
class TestAppModule() { ... }
当我运行应用程序时,它可以工作,但是当我运行测试时,GameActivity
没有被注入。所有带有@Inject
的字段都为null。
有人知道问题出在哪里吗?
如果有用的话,整个代码和测试在这里:
https://github.com/lucasnlm/antimine-android/pull/95https://github.com/lucasnlm/antimine-android/pull/95/commits/fcc1b3782b8d456898529dd3ba2410ac5f2da6d5
编辑:
我不知道为什么,在此PR上测试通过了:
kapt
运行测试也可以,但是会失败,因为它们没有被注入。 - Lucas Lima