[mocktio] 模拟测试框架

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

 

mock object with mock(Class);ide

 

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,可使用@

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture()); //验证调用的参数是否正确,可使用@
 assertEquals("John", argument.getValue().getName());

 可使用//given //when //then 风格SpyCaptor
相关文章
相关标签/搜索