Android Kotlin Testing. lateinit property _db has not been initialized

Viewed 2110

My code:

abstract class DbTest {

    @Rule
    @JvmField
    val countingTaskExecutorRule = CountingTaskExecutorRule()

    private lateinit var _db : AppDatabase

    val db: AppDatabase
        get() = _db

    @Before
    fun initDb() {
        _db = Room.inMemoryDatabaseBuilder(
                InstrumentationRegistry.getInstrumentation().context,
                AppDatabase::class.java
        ).build()
    }

    @After
    fun closeDb() {
        countingTaskExecutorRule.drainTasks(10, TimeUnit.SECONDS)
        _db.close()
    }
}

@RunWith(AndroidJUnit4::class)
class PlantDaoTest : DbTest() {

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @Test
    fun insert_one_plant() {
        val plant = Plant(plantId = 1, name="Plant1")
        db.plantDao.insertOnePlant(plant)

        val retrievedPlant = db.plantDao.getPlant(1)
        assert(plant.name==retrievedPlant.name)

    }
}

When I run PlantDaoTest, I see this error: kotlin.UninitializedPropertyAccessException: lateinit property _db has not been initialized

I really don't know how to fix this. Please help

4 Answers

I was having the same error, what I did to fix it was change all occurances of the annotationProcessor to kapt

in the app level build.gradle.

From:

 annotationProcessor 'androidx.room:room-compiler:2.2.3'

To:

kapt 'androidx.room:room-compiler:2.2.3'

Then I added this line to the top of the file:

apply plugin: 'kotlin-kapt'

Hope it Helps

I got the same issue during create the test for a database. After finding the solution for it, I got that I did not declare AppDatabse class as Database. And I think you did the same mistake.

So add annotation @Database and declare your AppDatabase as a database like below:

    @Database(entities = [Plant::class], version = 1, exportSchema = false)
    abstract class DbTest {
    ......

Put this line on abstract class DbTest {

Happy Coding..!

For me, It happened when I enabled Proguard So simply make sure that minifyEnabled false

Like that

  debug {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  }

Tried many solutions but only that worked for me was the identification of one silly mistake and addition of one build dependency which was missing in my case let me share details:

1 - Add this dependency if not there in your app level gradle.build.

kapt 'androidx.room:room-compiler:2.4.2'

2 - Make sure your dao interface methods are annotated with correct annotations like in my case I accidentally typed one annotation with "DELETE" which is annotation from HttpIntercepter class i guess while room's annotated looks like this: "Delete"

Hope these points will solve someones issue.

Related