《mockito 使用筆記》

oxoxooxx發表於2012-04-05

《mockito 使用筆記》
1.mock物件的建立
Iterator iter = mock(Iterator.class);
2.mock物件的使用
when(iter.next()).thenReturn("Hello").thenReturn("World");
3.mock物件方法呼叫校驗
verify(iter,time(2)).next();
4.多次呼叫同一個方法返回不同的值
when(iter.next()).thenReturn("hello").thenReturn("world");
5.對返回void或exception的特殊處理
//DemoMock demoMock = mock(DemoMock.class);
doNothing().when(demoMock).rowDelete(any(String.class));
doThrow((Exception) ret).when(demoMock).rowDelete(any(String.class));
6.對Mock物件方法的呼叫次數、順序和超時進行驗證
6.1驗證方法呼叫的次數:
verify(mock,atLeast(2)).someMethod();
never()
atLeast(N)
atLeastOnce()
atMost(N)

6.2超時驗證:
verify(mock,timeout(100).atLeast(2)).someMethod();
verify(mock,new Timeout(100,yourOwnVerifcationMode).someMethod();

6.3驗證方法呼叫的順序:
List firstMock = mock(List.class);
List secondMock = mock(List.class);
firstMock.add("called fitst");
firstMock.add("called fitst");
secondMock.add("called second");
secondMock.add("called third");
firstMock.add("called fitst");
InOrder inorder = inOrder(secondMock,firstMock);
inorder.verify(firstMock,times(2)).add("called fitst");
inorder.verify(secondMock,times(2)).add(anyBytes());
inOrder.verifyNoMoreInteractions();

7.mock引數校驗
class IsListOfTwoElement extends ArgumentMatcher{
public boolean matches(Object list){
return ((Lis)list).size()==2);
}
}
@Test
public void argumentMatchersTest(){
List mock = mock(List.class);
when(mock.addAll(argThat(new IsListOfTwoElement()))).thenReturn(true);
mock.addAll(Array.asList("one","two","three"));
verify(mock).addAll(argThat(new IsListOfTwoElement))));
}

8.Answer介面的使用:
List mock = mock(List.class);
when(mock.get(4)).thenAnswer(new MyAnswer());
#doAnser(new xxxAnswer()).when(mock).clear();
對於void方法可以指定Answer來進行返回處理,如:
doAnswer(new xxxAnswer()).when(mock).clear();

public class DemoAnswer implements Answer {
public DemoAnswer () {
}

public T answer(InvocationOnMock inv) throws Exception {
//TODO
return xx;
}

9.Mock annotations:
0.Annotation需要初始化才能使用Mock註解
在Junit4的@Before中進行初始化
@Before
public void initMocks(){
MockitoAnnotions.initMocks(this);
}

或者:

@RunWith(MockJUnit44Runner.class)
public class ExampleTset{
}

1.使用Mock註解定mock物件
@Mock
private AritcleDatabase database;

註解
註解
註解

10.一個簡單的例子:
Iterator i = mock(Iterator.class);
when(iter.next()).thenReturn("Hello").thenReturn("World");
String resutlt = i.next() + "" i.next();
verify(i,time(2)).next();
assertEqual("Hello World",resutlt);

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/23937368/viewspace-1057828/,如需轉載,請註明出處,否則將追究法律責任。

相關文章