mockito5.4.0单元测试(5) --校验mock对象的某种方法的准确调用次数

发布时间 2023-06-20 16:02:04作者: 梦幻朵颜

 

mokito官方文档地址: https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#exact_verification

// mock一个对象
LinkedList mockedList = mock(LinkedList.class);
// 使用mock对象来操作
mockedList.add("once");   // 添加"once"一次

mockedList.add("twice");  // 添加"twice"一次
mockedList.add("twice");  // 添加"twice"二次

mockedList.add("three times");  // 添加"three times"一次
mockedList.add("three times");  // 添加"three times"二次
mockedList.add("three times");  // 添加"three times"三次

//following two verifications work exactly the same - times(1) is used by default
verify(mockedList).add("once");   // 校验是否添加了"once"
verify(mockedList, times(1)).add("once");  // 校验添加了"once"一次

//exact number of invocations verification
verify(mockedList, times(2)).add("twice");  // 校验添加了"twice"二次
verify(mockedList, times(3)).add("three times");  // 校验添加了"three times"三次

//verification using never(). never() is an alias to times(0)
verify(mockedList, never()).add("never happened");  // 校验从未添加过"never happened"

//verification using atLeast()/atMost()
verify(mockedList, atMostOnce()).add("once");  // 校验最多添加过一次"once"
verify(mockedList, atLeastOnce()).add("three times");  // 校验至少添加过一次"three times"
verify(mockedList, atLeast(2)).add("three times");  // 校验至少添加过二次"three times"
verify(mockedList, atMost(5)).add("three times");  // 校验最多添加过五次"three times"

 

 

end.