Mockito (一)

几个概念

Mock

Stub

Spy

使用

多次调用返回不同的结果

1 when(mock.someMethod("some arg"))
2    .thenThrow(new RuntimeException())  // 第一次会抛出异常
3    .thenReturn("foo"); // 第二次会返回这个结果
4 //First call: throws runtime exception:
5 mock.someMethod("some arg"); // 第一次
6 //Second call: prints "foo"
7 System.out.println(mock.someMethod("some arg")); // 第二次
8 //Any consecutive call: prints "foo" as well (last stubbing wins).
9 System.out.println(mock.someMethod("some arg")); // 第n次(n> 2),依旧以最后返回最后一个配置

部分Mock - spy

3 //you can enable partial mock capabilities selectively on mocks:
4 Foo mock = mock(Foo.class);
5 //Be sure the real implementation is 'safe'.
6 //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
7 when(mock.someMethod()).thenCallRealMethod();

 

 1 List list = new LinkedList();
 2 List spy = spy(list);
 3 //optionally, you can stub out some methods:
 4 when(spy.size()).thenReturn(100);
 5 //using the spy calls *real* methods
 6 spy.add("one");
 7 spy.add("two");
 8 //prints "one" - the first element of a list
 9 System.out.println(spy.get(0));
10 //size() method was stubbed - 100 is printed
11 System.out.println(spy.size());
12 //optionally, you can verify
13 verify(spy).add("one");
14 verify(spy).add("two");

Mock 依赖Bean

使用@InjectMocks,自动将模拟对象或侦查域注入到被测试对象中。

// FileService 依赖 FileDao
@InjectMocks
@Autowired
private FileService fileService;

@Mock
private FileDao fileDao;

更多的使用方法可以参考Mockito浅谈

参考

转载于:https://www.cnblogs.com/tonyq/p/7599225.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值