Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Kotlin Testing. lateinit property _db has not been initialized

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

like image 230
MM TT Avatar asked Oct 20 '18 08:10

MM TT


1 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

like image 120
Doilio Matsinhe Avatar answered Nov 03 '22 01:11

Doilio Matsinhe