首页 > 解决方案 > org.mockito.exceptions.verification.NoInteractionsWanted:单元测试失败 - MVI 架构

问题描述

我已经为 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它说它被调用的那个方法是什么,我怎样才能将它添加到我的测试中。

标签: androidunit-testingkotlinmockito

解决方案


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


推荐阅读