Getting failed in providing HiltTestApplication as a dependency in my test module

1.9k Views Asked by At

I have followed this guide and trying to run instrumented test with HILT.But its getting failed in providing HiltTestApplication as a dependency in my test module. Below is my module class-

@ExperimentalCoroutinesApi
@FlowPreview
@Module
@TestInstallIn(components = [SingletonComponent::class],
    replaces = [ProductionModule::class])
object TestModule {

    @JvmStatic
    @Singleton
    @Provides
    fun provideRecipeDb(app: HiltTestApplication): RecipeDatabase {
        return Room
            .inMemoryDatabaseBuilder(app, RecipeDatabase::class.java)
            .fallbackToDestructiveMigration()
            .build()
    }
}

Got below error-

C:\Users\bhuvn\AndroidStudioProjects\Dairy\app\build\generated\source\kapt\debugAndroidTest\com\bhuvnesh\diary\framework\dataSource\cache\RecipeDaoServiceTests_HiltComponents.java:128: error: [Dagger/MissingBinding] dagger.hilt.android.testing.HiltTestApplication cannot be provided without an @Inject constructor or an @Provides-annotated method.
public abstract static class SingletonC implements RecipeDaoServiceTests_GeneratedInjector, ^ dagger.hilt.android.testing.HiltTestApplication is injected at com.bhuvnesh.diary.di.TestModule.provideRecipeDataFactory(application, �) com.bhuvnesh.diary.framework.dataSource.data.RecipesDataFactory is injected at com.bhuvnesh.diary.framework.dataSource.cache.RecipeDaoServiceTests.recipeDataFactory com.bhuvnesh.diary.framework.dataSource.cache.RecipeDaoServiceTests is injected at com.bhuvnesh.diary.framework.dataSource.cache.RecipeDaoServiceTests_GeneratedInjector.injectTest(com.bhuvnesh.diary.framework.dataSource.cache.RecipeDaoServiceTests) It is also requested at: com.bhuvnesh.diary.di.TestModule.provideRecipeDb(app)

I also tried by manually providing dependency in same module using-

    @JvmStatic
    @Singleton
    @Provides
    fun provideHiltTestApplication():HiltTestApplication{
        return HiltTestApplication()
    }

But it provides a null object which results in nullpointerexception.

1

There are 1 best solutions below

0
On

To provide the application context, you need to replace app: HiltTestApplication with @ApplicationContext app: Context because HiltTestApplication is the base application that can be used for Android instrumentation or Robolectric tests using Hilt, but it has to be specified in its annotations ( Like this @Config(application = HiltTestApplication::class) ). So, to provide the context in a method, you need to add the predefined qualifier to provide it. Check these out