【发布时间】:2020-04-16 08:57:13
【问题描述】:
我有一个函数可以使用包含 lambda 的事件更新 ViewModel Livedata。 () -> Unit 我想测试我的 lambda 是否在我的 LiveData 中返回。使用 Assert.equals 可以轻松完成对象,但现在使用 lambda 我不知道该怎么做。
这是我到目前为止得到的。
fun retrieveData() : {
viewModelScope.launch{
val myData = usecase.retrieveData()
if (myData != null) myDataLiveData.value = myData
else errorLiveData.value = Event { return@MyViewModel.retrieveData() }
}
}
在我的测试中我有:
subject.errorLiveData.observeForTesting {
assert(subject.errorLiveData.value!!.peekContent() != null) // This "works" but shows a hint that the comparison is always true even if I try it with == null and the assertion fails
}
这也是 Event 类。
/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
谢谢
【问题讨论】:
标签: android testing kotlin junit android-livedata