我的代码:
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 尚未初始化
我真的不知道如何解决这个问题。请帮忙
我遇到了同样的错误,我所做的修复是将 annotationProcessor
的所有出现更改为 kapt
在应用级别 build.gradle
。
来自:
annotationProcessor 'androidx.room:room-compiler:2.2.3'
收件人:
kapt 'androidx.room:room-compiler:2.2.3'
然后我将这一行添加到文件的顶部:
apply plugin: 'kotlin-kapt'
希望对你有帮助
我是一名优秀的程序员,十分优秀!