java mock框架 —— Mcktio

Mock的定义

在面向对象程序设计中,模拟对象是以可控的方式模拟真实对象行为的假对象

为什么使用Mock

在单元测试中,模拟对象可以模拟复杂的、真实的对象的行为,如果真实的对象无法放入单元测试中,可以使用模拟对象。

测试驱动的开发(TDD)要求我们先写单元测试,在写实现代码,在写单元测试的过程中,我们往往会遇到要测试的类有很多依赖,这些依赖的类型、对象、资源又有别的依赖,从而形成一个大的依赖树,要在单元测试的环境中完整的构建这样的依赖,是一件很困难事情,A < B > C, 我们要测试B就需要mockAC 

Mocktio是什么

mocktio是mock框架,可以用简洁的API做测试

 

使用Mocktio

maven

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.23.4</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13-beta-1</version>
</dependency>

gradle

compile("org.mockito:mockito-core:2.23.4")

 

1. 验证行为

 //Let's import Mockito statically so that the code looks clearer
 import static org.mockito.Mockito.*;

 //模拟List对象
 List mockedList = mock(List.class);

 //模拟一些行为
 mockedList.add("one");
 mockedList.clear();

 //验证行为是否发生
 verify(mockedList).add("one");
 verify(mockedList).clear();

 

2. 模拟期望结果

 LinkedList mockedList = mock(LinkedList.class);

 // 打桩
 when(mockedList.get(0)).thenReturn("first");
 when(mockedList.get(1)).thenThrow(new RuntimeException());

 // 输出first
 System.out.println(mockedList.get(0));

 //throws runtime exception
 System.out.println(mockedList.get(1));

 // 输出null
 System.out.println(mockedList.get(999));

 //Although it is possible to verify a stubbed invocation, usually it's just redundant
 //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
 //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.
 verify(mockedList).get(0);

未完待续……

转载于:https://www.cnblogs.com/dawangele/p/10324295.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值