我有一个方法,该方法从Room的DAO层获取LiveData对象,然后对该LiveData对象进行一些操作。
每当我尝试执行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
}
然后做
dataStorage.getAllSections.blockingObserve()
单元测试运行良好。我没有得到一个空指针异常。
我什至尝试使用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
}
这是我的测试用例:
@Test
fun test_buildDataFromDb() = runBlocking {
val result = appDataProvider.buildDataFromDB().blockingObserve()
// asserts
}