美文网首页
Mockito Verify常见用法

Mockito Verify常见用法

作者: 一路花开_8fab | 来源:发表于2019-04-15 16:40 被阅读0次

    该系列文章翻译自https://www.baeldung.com/mockito-series

    下面将以MyList类为例进行介绍

    public class MyList extends AbstractList<String> {
     
        @Override
        public String get(final int index) {
            return null;
        }
        @Override
        public int size() {
            return 0;
        }
    }
    

    Verify常见用法

    1. 校验调用了某个方法

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

    2. 校验调用某个方法的次数

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

    3. 校验没有调用任何方法

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

    4. 校验没有调用某个方法

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

    或者

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

    5. 判断是否有没有被校验的调用

    List<String> mockedList = mock(MyList.class);
    //interactions
    mockedList.size();
    mockedList.clear();
    //verification
    verify(mockedList).size();
     //following will fail because 'clear()' is unexpected
    verifyNoMoreInteractions(mockedList);
    

    6. 校验调用的顺序

    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();
    

    7. 校验某个方法至少/至多调用的次数

    List<String> mockedList = mock(MyList.class);
    mockedList.clear();
    mockedList.clear();
    mockedList.clear();
     
    verify(mockedList, atLeast(1)).clear();
    verify(mockedList, atMost(10)).clear();
    

    8. 校验调用某个方法时使用了特定的参数

    固定参数

    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());
    

    9. 使用参数捕获器

    List<String> mockedList = mock(MyList.class);
    mockedList.addAll(Lists.<String> newArrayList("someElement"));
    ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
    verify(mockedList).addAll(argumentCaptor.capture());
    List<String> capturedArgument = argumentCaptor.<List<String>> getValue();
    assertThat(capturedArgument, hasItem("someElement"));
    

    相关文章

      网友评论

          本文标题:Mockito Verify常见用法

          本文链接:https://www.haomeiwen.com/subject/pxzuwqtx.html