繁体   English   中英

如何测试 lambda 从 Kotlin 中的 function 返回

[英]How can I test that a lambda is returned from a function in Kotlin

我有一个 function,它使用包含 lambda 的事件更新 ViewModel Livedata。 () -> Unit ,我想测试我的 lambda 是否在我的 LiveData 中返回。 使用 object 很容易使用 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
    }

这也是事件 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
}

我从这里拿它:https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

谢谢

您可以在 kotlin...

subject.errorLiveData?.apply{
   assert(this.value.peekContent())
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM