我目前正在開發一個應用程序,使用新的Android Architecture Components。具體來說,我正在實現一個房間數據庫,它在其中一個查詢上返回一個LiveData
對象。插入和查詢按預期工作,但我有一個問題使用單元測試來測試查詢方法。單元測試室和LiveData
這裏是DAO我想測試:
NotificationDao.kt
@Dao
interface NotificationDao {
@Insert
fun insertNotifications(vararg notifications: Notification): List<Long>
@Query("SELECT * FROM notifications")
fun getNotifications(): LiveData<List<Notification>>
}
正如你所知道的,查詢函數返回一個LiveData
對象,如果我改變這只是一個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對象的單元測試嗎?
版本1.0.0中是否有更新? –