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