[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
相關文章
相關標籤/搜索