首页 > 解决方案 > 为什么实时数据测试总是返回 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 实现编写测试。但是,当我尝试观察实时数据时,我总是得到一个空值。在实际应用程序中它运行完美,但是当我运行测试时,我总是得到一个空值。我该如何解决这个问题?

标签: androidandroid-roomandroid-livedataandroid-testing

解决方案


推荐阅读