Android 单元测试从方法内部的房间返回的LiveData
我有一个方法,它从房间的DAO层获取LiveData对象,然后对LiveData对象执行一些操作 每当我尝试执行Android 单元测试从方法内部的房间返回的LiveData,android,junit,android-room,android-livedata,android-instrumentation,Android,Junit,Android Room,Android Livedata,Android Instrumentation,我有一个方法,它从房间的DAO层获取LiveData对象,然后对LiveData对象执行一些操作 每当我尝试执行dataStorage.getAllSections()时,它都会返回一个LiveData对象,并且该值始终为null。(我的数据库已预填充) 我已经为LiveData声明了JUnit规则 @get:Rule val rule = InstantTaskExecutorRule() 在我的实际类中,如果我创建一个扩展函数来像这样等待LiveData private fun <T
dataStorage.getAllSections()
时,它都会返回一个LiveData对象,并且该值始终为null。(我的数据库已预填充)
我已经为LiveData声明了JUnit规则
@get:Rule
val rule = InstantTaskExecutorRule()
在我的实际类中,如果我创建一个扩展函数来像这样等待LiveData
private fun <T> LiveData<T>.blockingObserve(): T? {
var value: T? = null
val latch = CountDownLatch(1)
val observer = Observer<T> { t ->
value = t
latch.countDown()
}
observeForever(observer)
latch.await(2, TimeUnit.SECONDS)
return value
}
单元测试运行良好。我没有得到空指针异常。
我甚至尝试过使用runBlocking
运行测试,但这也没有帮助
This is my method I am trying to test:
@VisibleForTesting
fun buildDataFromDB(): LiveData<List<SectionModel>> {
Logger.d(TAG, "Building data from DB")
val sections = dataStorage.getAllSections()
// sections.value is always null even though my DB is populated
sections.value?.forEach { section ->
// Do something
}
}
Logger.d(TAG, "Building data from DB completed")
return sections
}
This is my method I am trying to test:
@VisibleForTesting
fun buildDataFromDB(): LiveData<List<SectionModel>> {
Logger.d(TAG, "Building data from DB")
val sections = dataStorage.getAllSections()
// sections.value is always null even though my DB is populated
sections.value?.forEach { section ->
// Do something
}
}
Logger.d(TAG, "Building data from DB completed")
return sections
}
@Test
fun test_buildDataFromDb() = runBlocking {
val result = appDataProvider.buildDataFromDB().blockingObserve()
// asserts
}