I have a function that updates a ViewModel Livedata with an Event which contains a lambda. () -> Unit
and I want to test that my lambda is returned in my LiveData. With an object was easily done with an Assert.equals but now with a lambda I have no idea how to do it.
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.
/**
* 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
Thanks
You can use lambda function as below in kotlin...
subject.errorLiveData?.apply{
assert(this.value.peekContent())
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.