《mockito 使用笔记》

本文详细介绍Mockito框架的基本用法,包括mock对象创建、方法调用校验、参数校验及Answer接口使用等,并通过示例讲解如何进行方法调用次数、顺序验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《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;

2.@Spy注解
3.@Captor注解
4.@InjectMocks注解

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/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/23937368/viewspace-1057828/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值