android - 为什么实时数据测试总是返回 null?
问题描述
@InternalCoroutinesApi
@ExperimentalCoroutinesApi
@Config(sdk = [Build.VERSION_CODES.O_MR1])
@RunWith(RobolectricTestRunner::class)
class PostRepositoryTest {
private lateinit var postDao: RoomPostDao
private val user = User(userID = 109, username = "andrei", email = "andrei@yahoo.com", profilePicture = "sdfs")
private val testPost = Post.buildTestPost()
@Before
@Throws(Exception::class)
fun setUp() {
//use a cache version of the database
val db = Room.inMemoryDatabaseBuilder(
InstrumentationRegistry.getInstrumentation().targetContext,
PostDatabase::class.java
).build()
postDao = db.postDao()
runBlocking {
db.userDao().insertUser(user)
db.postDao().insertPost(testPost)
}
}
@Test
fun shouldReturnNotNullCachedPosts() {
val liveData = postDao.getCachedPosts()
Assert.assertNotNull(liveData.getOrAwaitValue())
}
fun <T> LiveData<T>.getOrAwaitValue(
time: Long = 10,
timeUnit: TimeUnit = TimeUnit.SECONDS
): T {
var data: T? = null
val latch = CountDownLatch(1)
val observer = object : Observer<T> {
override fun onChanged(o: T?) {
data = o
latch.countDown()
this@getOrAwaitValue.removeObserver(this)
}
}
this.observeForever(observer)
// Don't wait indefinitely if the LiveData is not set.
if (!latch.await(time, timeUnit)) {
throw TimeoutException("LiveData value was never set.")
}
@Suppress("UNCHECKED_CAST")
return data as T
}
}
@Query("SELECT * FROM post ORDER BY postID DESC")
fun getCachedPosts(): LiveData<List<Post>>
我正在尝试为我的 Room Dao 实现编写测试。但是,当我尝试观察实时数据时,我总是得到一个空值。在实际应用程序中它运行完美,但是当我运行测试时,我总是得到一个空值。我该如何解决这个问题?
解决方案
推荐阅读
- javascript - 选择 2 和 flatpicker 选项显示在下方/上方输入的顶部
- base64 - blazor html图像标签转换为pdf
- java - 在改造后的请求中传递数组问题
- javascript - 如何使用离子显示当前日期和时间
- reactjs - 如何在 Gatsby Js 项目中管理状态
- python - 如何在 pandas DataFrame 中找到最大连续负数数
- c# - 正则表达式在字符串中任何特定单词之前和之后查找特定单词
- windows - 从 Mac 访问 Windows 虚拟机上的 localhost
- c# - 有没有办法在 github 的 ci-cd 中显示代码覆盖率结果指标?
- angular - Angular 设置动态条形图数据和标签