org.mockito.exceptions.verification.NoInteractionsWanted:单元测试失败-MVI结构

时间:2020-03-30 13:57:55

标签: android unit-testing kotlin mockito

我已经为Android应用程序实现了MVI结构,但是我无法编写任何成功的测试。

这是一个示例:

fun verifyLoadStateSuccess() {

    val loading= State(isLoading = true)
    val loaded = State(list)

    whenever(listUseCase.loadList()).thenReturn(Observable.just(list))

    viewModel.dispatch(Action.Load)
    testSchedulerRule.triggerActions()

    inOrder(testObserver) {
        verify(testObserver).onChanged(loading)
        verify(testObserver).onChanged(loaded)
    }

    verifyNoMoreInteractions(testObserver) // if i comment this line, the test pass ok
}

我得到的错误是:

No interactions wanted here:
-> at com.nhaarman.mockito_kotlin.MockitoKt.verifyNoMoreInteractions(Mockito.kt:258)
But found this interaction on mock 'observer':
-> at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131)
***
For your reference, here is the list of all invocations ([?] - means unverified).
1. [?]-> at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131)

我已经用调试器运行了代码,并在reducer上进行了检查,如何调用时间和state的值,但只有正确的值两次。

我不知道它所说的被调用的considerNotify方法是什么,以及如何将其添加到测试中。

1 个答案:

答案 0 :(得分:0)

这意味着您的观察者 onChanged 正在被更多事件调用。在运行测试时,在实时数据的 thinkNotify 方法中保持一个断点。您会看到比您认为触发的事件更多,因此测试失败。