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 风格
  • 相关阅读:
    Webform中linq to sql多条件查询(小练习)
    Webform购物车(用Session存储,页面传值)
    C#操控条形码扫描枪
    C#汉字转拼音首字母
    简单的实现QQ通信功能(五)
    简单的实现QQ通信功能(四)
    简单的实现QQ通信功能(三)
    简单的实现QQ通信功能(二)
    简单的实现QQ通信功能(一)
    利用数据集进行数据访问操作
  • 原文地址:https://www.cnblogs.com/zengyou/p/3651862.html
Copyright © 2011-2022 走看看