Home > Net >  Hilt - Unit Tests
Hilt - Unit Tests

Time:04-03

I would like to start using Hilt in my test.

Gradle:

android{
...
defaultConfig{
...
testInstrumentationRunner "com.rachapps.myfitapp.HiltTestRunner"
}
androidTestImplementation 'com.google.dagger:hilt-android-testing:2.28-alpha'
kaptAndroidTest 'com.google.dagger:hilt-android-compiler:2.38.1'

...

class HiltTestRunner : AndroidJUnitRunner() {

    override fun newApplication(
        cl: ClassLoader?,
        className: String?,
        context: Context?
    ): Application {
        return super.newApplication(cl, HiltTestApplication::class.java.name, context)
    }
}

test class:

@SmallTest
@HiltAndroidTest
class BodyPartDaoTest {

    @get : Rule
    var hiltRule = HiltAndroidRule(this)

    @get : Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @Inject
    @Named("test_db")
    lateinit var database: MyFitDatabase

    private lateinit var bodyPartDao: BodyPartDao
    private lateinit var exerciseDao: ExerciseDao

    @Before
    fun setup() {
        hiltRule.inject()
        bodyPartDao = database.bodyPartDao()
        exerciseDao = database.exerciseDao()
    }
...
}

Module:

@Module
@InstallIn(SingletonComponent::class)
object TestAppModule {
    @Provides
    @Named("test_db")
    fun provideInMemoryDb(@ApplicationContext context: Context) : MyFitDatabase {
        return Room.inMemoryDatabaseBuilder(context, MyFitDatabase::class.java).allowMainThreadQueries().build()
    }
}

While executing test I receive an error:

C:\Radek\Android\MyFitApp\app\build\generated\source\kapt\debugAndroidTest\com\rachapps\myfitapp\data\dao\BodyPartDaoTest_TestComponentDataSupplier.java:14: error: BodyPartDaoTest_TestComponentDataSupplier is not abstract and does not override abstract method get() in TestComponentDataSupplier
public final class BodyPartDaoTest_TestComponentDataSupplier extends TestComponentDataSupplier {
             ^
C:\Radek\Android\MyFitApp\app\build\generated\source\kapt\debugAndroidTest\com\rachapps\myfitapp\data\dao\BodyPartDaoTest_TestComponentDataSupplier.java:15: error: get() in BodyPartDaoTest_TestComponentDataSupplier cannot override get() in TestComponentDataSupplier
  protected TestComponentData get() {
                              ^
  return type TestComponentData is not compatible with Map<Class<?>,TestComponentData>
2 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugAndroidTestJavaWithJavac'.

CodePudding user response:

I am not sure as to what is the reason for the exception, but the way you are providing in-memory DB to the test, is not what the documentation says you should do.

Try replacing the binding, and see what happens.

CodePudding user response:

I had that problem because of outdated library: com.google.dagger:hilt-android-testing

  • Related