У меня есть функция, которая обновляет LiveData ViewModel с событием, которое содержит лямбду. () -> Unit
и я хочу проверить, что моя лямбда возвращается в моих LiveData. С объектом легко было сделать с помощью Assert.equals, но теперь с лямбдой я понятия не имею, как это сделать.
Вот что я получил до сих пор.
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
}
Я беру его отсюда: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150
Спасибо