1. 概述

在 Mockito verify 用于验证某个方法是否被调用,以及调用的次数和参数。本文我们 通过示例演示 Mockito verify 的各种用法

下面是我们将要 mock 的 List:

public class MyList extends AbstractList<String> {

    @Override
    public String get(final int index) {
        return null;
    }

    @Override
    public int size() {
        return 1;
    }
}

2. The Cookbook

简单验证:

List<String> mockedList = mock(MyList.class);
mockedList.size();

// 验证 size() 方法是否被调用
verify(mockedList).size();

验证mock的调用次数:

List<String> mockedList = mock(MyList.class);
mockedList.size();
// 验证 size() 方法是否被调用了 1 次
verify(mockedList, times(1)).size();

验证 mock 对象的所有方法都没有被调用:

List<String> mockedList = mock(MyList.class);
verifyNoInteractions(mockedList);

验证 mock 的某个方法被调用:

List<String> mockedList = mock(MyList.class);
verify(mockedList, times(0)).size();

验证没有额外的调用:

List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.clear();

verify(mockedList).size();
// 除了 size() 外,clear()也被调用了,所以下面会抛出异常
assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList));

验证调用顺序:

List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.add("a parameter");
mockedList.clear();

InOrder inOrder = Mockito.inOrder(mockedList);
inOrder.verify(mockedList).size();
inOrder.verify(mockedList).add("a parameter");
inOrder.verify(mockedList).clear();

验证没有调用某个方法:

List<String> mockedList = mock(MyList.class);
mockedList.size();

verify(mockedList, never()).clear();

验证至少调用次数:

List<String> mockedList = mock(MyList.class);
mockedList.clear();
mockedList.clear();
mockedList.clear();

verify(mockedList, atLeast(1)).clear();
verify(mockedList, atMost(10)).clear();

验证调用时实际传入的参数:

List<String> mockedList = mock(MyList.class);
mockedList.add("test");

verify(mockedList).add("test");

验证调用时传入的参数,不关心具体值:

List<String> mockedList = mock(MyList.class);
mockedList.add("test");

verify(mockedList).add(anyString());

验证调用时传入的参数,并捕获参数:

List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String> newArrayList("someElement"));

ArgumentCaptor<List<String>> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());

List<String> capturedArgument = argumentCaptor.getValue();
assertThat(capturedArgument).contains("someElement");

3. 总结

我还发布了一些类似的开发手册,如 Google GuavaHamcrest

文中的示例和代码片段可以在 GitHub 上找到。


« 上一篇: Guava Functional 用例
» 下一篇: Mockito When/Then 用法