[英]How can I test that a lambda is returned from a function in Kotlin
I have a function that updates a ViewModel Livedata with an Event which contains a lambda.我有一个 function,它使用包含 lambda 的事件更新 ViewModel Livedata。
() -> Unit
and I want to test that my lambda is returned in my LiveData. () -> Unit
,我想测试我的 lambda 是否在我的 LiveData 中返回。 With an object was easily done with an Assert.equals but now with a lambda I have no idea how to do it.使用 object 很容易使用 Assert.equals 完成,但现在使用 lambda 我不知道该怎么做。
Here's what I got until now.这是我到目前为止所得到的。
fun retrieveData() : {
viewModelScope.launch{
val myData = usecase.retrieveData()
if (myData != null) myDataLiveData.value = myData
else errorLiveData.value = Event { return@MyViewModel.retrieveData() }
}
}
In my test I have:在我的测试中,我有:
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
}
Here's also the Event class.这也是事件 class。
/**
* 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
}
I take it from here: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150我从这里拿它:https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150
Thanks谢谢
You can use lambda function as below in kotlin...您可以在 kotlin...
subject.errorLiveData?.apply{
assert(this.value.peekContent())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.