【问题标题】:How can I test that a lambda is returned from a function in Kotlin如何测试从 Kotlin 中的函数返回的 lambda
【发布时间】: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
}

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

谢谢

【问题讨论】:

    标签: android testing kotlin junit android-livedata


    【解决方案1】:

    您可以在 kotlin 中使用如下 lambda 函数...

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

    【讨论】:

    • assert(it) 需要一个布尔值作为参数,不接受 lambda :(
    • 这行不通,因为 peekContent() 返回一个 lambda () -> 单位不是布尔值,这就是 assert 不起作用的原因。我已经在测试中尝试过了。
    • 请立即查看
    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2019-08-21
    • 2016-12-26
    • 1970-01-01
    • 2015-08-27
    相关资源
    最近更新 更多