'Can't use HiltAndroidRule in testing Room Dao

I want use Hilt for Room Dao testing. I learned from this project https://github.com/philipplackner/ShoppingListTestingYT/tree/TestingWithHilt

My testing failed and show that:

java.lang.IllegalStateException: Hilt test, com.example.allinone.page2.testAndHilt.data.local.TestItemDaoTest, cannot use a @HiltAndroidApp application but found com.example.allinone.main.MainApplication. To fix, configure the test to use HiltTestApplication or a custom Hilt test application generated with @CustomTestApplication. at dagger.hilt.internal.Preconditions.checkState(Preconditions.java:83) at dagger.hilt.android.internal.testing.MarkThatRulesRanRule.(MarkThatRulesRanRule.java:63) at dagger.hilt.android.testing.HiltAndroidRule.(HiltAndroidRule.java:36) at com.example.allinone.page2.testAndHilt.data.local.TestItemDaoTest.(TestItemDaoTest.kt:27)

in AppModule:

@Module
@InstallIn(SingletonComponent::class)
object AppModuleTest {

    @Provides
    @Named("test_db")
    fun provideInMemoryDB(@ApplicationContext context: Context) =
        Room.inMemoryDatabaseBuilder(context, TestItemDataBase::class.java)
            .allowMainThreadQueries()
            .build()
}

in DaoTest:

@SmallTest
@HiltAndroidTest
//@RunWith(AndroidJUnit4::class)
class TestItemDaoTest {

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @Inject
    @Named("test_db")
    lateinit var database: TestItemDataBase
    lateinit var dao: TestItemDao

    @Before
    fun setup() {
        hiltRule.inject()
        dao = database.testItemDao()
    }

    @After
    fun teardown() {
        database.close()
    }

    @Test
    fun test() {
        assertEquals(1, 1)
    }
}

Where is the problem? I didn't use MainApplication. And I want use

hiltRule.inject()

so I don't know how to rewrite.



Solution 1:[1]

It is an IDE bug. Just invalidae cachs and restart.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barr