zoukankan      html  css  js  c++  java
  • [mocktio] 模拟测试框架

    http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html

    mock object with mock(Class);

    List mockedList = mock(List.class);

    可以使用 when(obj.somemethod())

    List mockedList = mock(List.class);
    
    verify(mockedList).add("one");//验证方法调用,可用atLeast,atMost,time,never等
    
    when(mockedList.get(0)).thenReturn("first"); //模拟返回值,亦可使用doReturn().when
    
    when(mockedList.get(1)).thenThrow(new RuntimeException()); //模拟抛出异常 doThrow().when
    
    when(mockedList.get(anyInt())).thenReturn("element"); //argument matcher,参见matcher class http://docs.mockito.googlecode.com/hg/org/mockito/Matchers.html
    
    InOrder inOrder = inOrder(firstMock, secondMock);
    inOrder.verify(firstMock).add("was called first");
    inOrder.verify(secondMock).add("was called second"); //验证mock对象的调用顺序
    
    @Mock private UserProvider userProvider;//mock注解,必须在baseclass中MockitoAnnotations.initMocks(testClass);
    
    when(mock.someMethod("some arg")).thenThrow(new RuntimeException()).thenReturn("foo");//连续迭代调用mock方法时的返回值,也可这样:when(mock.someMethod("some arg")).thenReturn("one", "two", "three");
    
    List list = new LinkedList();
    List spy = spy(list); //模拟一个真实的object,在1.8版本之后。mock对象无法模拟真实的函数,会overwirte所有方法,除却stub的方法,其余方法都无法模拟真实对象,spy对象可以使用真实的object和stub方法,
    //可调用when(mock.someMethod()).thenCallRealMethod();实现部分mock,可以使用@Spy
    
    ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
    verify(mock).doSomething(argument.capture()); //验证调用的参数是否正确,可以使用@Captor
     assertEquals("John", argument.getValue().getName());

     可以使用//given //when //then 风格
  • 相关阅读:
    Java.io.outputstream.PrintStream:打印流
    Codeforces 732F. Tourist Reform (Tarjan缩点)
    退役了
    POJ 3281 Dining (最大流)
    Light oj 1233
    Light oj 1125
    HDU 5521 Meeting (最短路)
    Light oj 1095
    Light oj 1044
    HDU 3549 Flow Problem (dinic模版 && isap模版)
  • 原文地址:https://www.cnblogs.com/zengyou/p/3651862.html
Copyright © 2011-2022 走看看