【问题标题】:Android Kotlin Testing. lateinit property _db has not been initialized安卓 Kotlin 测试。 lateinit 属性 _db 尚未初始化
【发布时间】:2018-10-20 08:05:05
【问题描述】:

我的代码:

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)

    }
}

当我运行 PlantDaoTest 时,我看到了这个错误: kotlin.UninitializedPropertyAccessException:lateinit 属性 _db 尚未初始化

我真的不知道如何解决这个问题。请帮忙

【问题讨论】:

    标签: android testing kotlin


    【解决方案1】:

    我遇到了同样的错误,我所做的解决方法是将所有出现的 annotationProcessor 更改为 kapt

    在应用级别build.gradle

    发件人:

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

    收件人:

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

    然后我将这一行添加到文件的顶部:

    apply plugin: 'kotlin-kapt'
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      我在为数据库创建测试时遇到了同样的问题。 在找到解决方案后,我发现我没有将 AppDatabse 类声明为数据库。 我认为你也犯了同样的错误。

      所以添加 annotation @Database 并将您的 AppDatabase 声明为如下所示的数据库:

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

      把这一行放在abstract class DbTest {

      编码愉快..!

      【讨论】:

        【解决方案3】:

        对我来说,它发生在我启用 Proguard 时 所以只需确保minifyEnabled false

        这样

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

        【讨论】:

          猜你喜欢
          • 2020-04-14
          • 1970-01-01
          • 2022-11-22
          • 2021-10-13
          • 2022-07-05
          • 1970-01-01
          • 1970-01-01
          • 2017-03-03
          • 1970-01-01
          相关资源
          最近更新 更多