我想验证与可能db模拟对象确实有x次交互。是否有类似于"verifyZeroInteractions(("方法的方法?
验证无交互((
与verifyZeroInteractions((完全相同的行为
Mockito.verify(MOCKED_OBJ, Mockito.times(number)).YOUR_METHOD_CALL();
Mockito.verify(MOCKED_OBJ, Mockito.atLeast(number)).YOUR_METHOD_CALL();
更多信息在这里
根据 mockito 文档,您可以使用 verify(mockedList, never()).add("never happened");
.
有很多有用的组合来检查您的预期行为。来自Mockito文档的其他示例:
//using mock
mockedList.add("once");
mockedList.add("twice");
mockedList.add("twice");
mockedList.add("three times");
mockedList.add("three times");
mockedList.add("three times");
//following two verifications work exactly the same - times(1) is used by default
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");
//exact number of invocations verification
verify(mockedList, times(2)).add("twice");
verify(mockedList, times(3)).add("three times");
//verification using never(). never() is an alias to times(0)
verify(mockedList, never()).add("never happened");
//verification using atLeast()/atMost()
verify(mockedList, atLeastOnce()).add("three times");
verify(mockedList, atLeast(2)).add("three times");
verify(mockedList, atMost(5)).add("three times");
或者您可以使用验证NoMoreInteraction来确保没有与您模拟的其他交互。
//using mocks
mockedList.add("one");
mockedList.add("two");
verify(mockedList).add("one");
//following verification will fail
verifyNoMoreInteractions(mockedList);
此外,您可以使用 inOrder 以完全相同的顺序验证多个模拟的交互,并添加 verifyNoMoreInteractions(( 以确保没有与您的模拟定义的其他交互。
InOrder inOrder = inOrder(firstMock, secondMock);
inOrder.verify(firstMock).add("was called first");
inOrder.verify(secondMock).add("was called second");
inOrder.verifyNoMoreInteractions();
查看 Mockito 文档 fo 感受 mockito 的全部力量:https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/Mockito.html
参见https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/Mockito.html#4https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/Mockito.html#8
Mockito.verify()
方法传递Mockito.times(...)
或Mockito.atLeast(..)
作为参数。
甚至更优雅
verify(MOCK, never()).method()