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 风格
  • 相关阅读:
    卷积神经网络的权值参数个数的量化分析
    Torch 的安装与基本用法
    Torch 的安装与基本用法
    操作系统的 (program)loader(程序加载器)
    操作系统的 (program)loader(程序加载器)
    Python 模块学习:os模块
    Python 正则表达式-OK
    Perl参考函数
    svn: E200030: sqlite[S10]: disk I/O error
    Perl调用外部命令的方式和区别
  • 原文地址:https://www.cnblogs.com/zengyou/p/3651862.html
Copyright © 2011-2022 走看看