我目前正在使用新的 Android Architecture Components 开发应用程序.具体来说,我正在实现一个房间数据库,它在其中一个查询上返回一个 LiveData
对象。插入和查询按预期工作,但是我在使用单元测试测试查询方法时遇到问题。
这是我要测试的 DAO:
NotificationDao.kt
@Dao
interface NotificationDao {
@Insert
fun insertNotifications(vararg notifications: Notification): List<Long>
@Query("SELECT * FROM notifications")
fun getNotifications(): LiveData<List<Notification>>
}
如您所知,如果我将其更改为 List
、Cursor
或基本上我得到了预期的结果,即插入数据库中的数据。
问题是下面的测试总是会失败,因为 LiveData
对象的 value
总是 null
:
NotificationDaoTest.kt
lateinit var db: SosafeDatabase
lateinit var notificationDao: NotificationDao
@Before
fun setUp() {
val context = InstrumentationRegistry.getTargetContext()
db = Room.inMemoryDatabaseBuilder(context, SosafeDatabase::class.java).build()
notificationDao = db.notificationDao()
}
@After
@Throws(IOException::class)
fun tearDown() {
db.close()
}
@Test
fun getNotifications_IfNotificationsInserted_ReturnsAListOfNotifications() {
val NUMBER_OF_NOTIFICATIONS = 5
val notifications = Array(NUMBER_OF_NOTIFICATIONS, { i -> createTestNotification(i) })
notificationDao.insertNotifications(*notifications)
val liveData = notificationDao.getNotifications()
val queriedNotifications = liveData.value
if (queriedNotifications != null) {
assertEquals(queriedNotifications.size, NUMBER_OF_NOTIFICATIONS)
} else {
fail()
}
}
private fun createTestNotification(id: Int): Notification {
//method omitted for brevity
}
所以问题是:有谁知道执行涉及 LiveData 对象的单元测试的更好方法?
最佳答案
当有观察者时,Room 会懒惰地计算 LiveData
的值。
您可以查看sample app .
它使用 getValue添加观察者以获取值的实用方法:
public static <T> T getOrAwaitValue(final LiveData<T> liveData) throws InterruptedException {
final Object[] data = new Object[1];
final CountDownLatch latch = new CountDownLatch(1);
Observer<T> observer = new Observer<T>() {
@Override
public void onChanged(@Nullable T o) {
data[0] = o;
latch.countDown();
liveData.removeObserver(this);
}
};
liveData.observeForever(observer);
latch.await(2, TimeUnit.SECONDS);
//noinspection unchecked
return (T) data[0];
}
使用 kotlin 更好,您可以将其作为扩展功能:)。
https://stackoverflow.com/questions/44270688/
相关文章:
kotlin - Kotlin 协程中的挂起函数是什么意思?
kotlin - 警告 : Kotlin runtime JAR files in the clas
kotlin - kotlin 中的 Dagger 2 静态提供程序方法
android - 如何将 Kotlin 与 Proguard 一起使用
android-studio - Kotlin:为什么 Android Studio 中的大多数变量
enums - 如何在 Kotlin 中为枚举创建 "static"方法?