Mockito框架入门教程(一)
官网: http://mockito.org
API文档:http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html
项目源码:https://github.com/mockito/mockito
在做单元测试的时候,有的时候用到的一些类,我们构造起来不是那么容易,比如HttpRequest,或者说某个Service依赖到了某个Dao,想构造service还得先构造dao,这些外部对象构造起来比较麻烦。 所以出现了Mock! 我们可以用 Mock 工具来模拟这些外部对象,来完成我们的单元测试。
关于什么时候需要Mock对象,Tim Mackinnon给我们了一些建议:
----- 真实对象具有不可确定的行为(产生不可预测的结果,如股票的行情)
----- 真实对象很难被创建(比如具体的web容器)
----- 真实对象的某些行为很难触发(比如网络错误)
----- 真实情况令程序的运行速度很慢
----- 真实对象有用户界面
----- 测试需要询问真实对象它是如何被调用的(比如测试可能需要验证某个回调函数是否被调用了)
----- 真实对象实际上并不存在(当需要和其他开发小组,或者新的硬件系统打交道的时候,这是一个普遍的问题)
实现Mock技术的优秀开源框架有很多,下面以Mockito为例,用几个简单例子来介绍Mock工具的基本使用:
首先添加maven依赖
加载mockito依赖:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
当然mockito需要junit或testng配合使用
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
testng依赖此处省略;
然后为了使代码更简洁,最好在测试类中导入静态资源
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
使用mockito来做测试:
下面我们开始使用mockito来做测试
1、验证行为
@Test
public void verify_behaviour(){
//模拟创建一个List对象
List mock = mock(List.class);
//使用mock的对象
mock.add(1);
mock.clear();
//验证add(1)和clear()行为是否发生
verify(mock).add(1);
verify(mock).clear();
}
2、模拟我们所期望的结果
@Test
public void when_thenReturn(){
//mock一个Iterator类
Iterator iterator = mock(Iterator.class);
//预设当iterator调用next()时第一次返回hello,第n次都返回world
when(iterator.next()).thenReturn("hello").thenReturn("world");
//使用mock的对象
String result = iterator.next() + " " + iterator.next() + " " + iterator.next();
//验证结果
assertEquals("hello world world",result);
}
@Test(expected = IOException.class)
public void when_thenThrow() throws IOException {
OutputStream outputStream = mock(OutputStream.class);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
//预设当流关闭时抛出异常
doThrow(new IOException()).when(outputStream).close();
outputStream.close();
}
3、参数匹配
@Test
public void with_arguments(){
Comparable comparable = mock(Comparable.class);
//预设根据不同的参数返回不同的结果
when(comparable.compareTo("Test")).thenReturn(1);
when(comparable.compareTo("Omg")).thenReturn(2);
assertEquals(1, comparable.compareTo("Test"));
assertEquals(2, comparable.compareTo("Omg"));
//对于没有预设的情况会返回默认值
assertEquals(0, comparable.compareTo("Not stub"));
}
除了匹配制定参数外,还可以匹配自己想要的任意参数
@Test
public void with_unspecified_arguments(){
List list = mock(List.class);
//匹配任意参数
when(list.get(anyInt())).thenReturn(1);
when(list.contains(argThat(new IsValid()))).thenReturn(true);
assertEquals(1, list.get(1));
assertEquals(1, list.get(999));
assertTrue(list.contains(1));
assertTrue(!list.contains(3));
}
private class IsValid extends ArgumentMatcher<List>{
@Override
public boolean matches(Object o) {
return o == 1 || o == 2;
}
}
需要注意的是如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配
@Test
public void all_arguments_provided_by_matchers(){
Comparator comparator = mock(Comparator.class);
comparator.compare("nihao","hello");
//如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配
verify(comparator).compare(anyString(),eq("hello"));
//下面的为无效的参数匹配使用
//verify(comparator).compare(anyString(),"hello");
}
4、验证确切的调用次数
@Test
public void verifying_number_of_invocations(){
List list = mock(List.class);
list.add(1);
list.add(2);
list.add(2);
list.add(3);
list.add(3);
list.add(3);
//验证是否被调用一次,等效于下面的times(1)
verify(list).add(1);
verify(list,times(1)).add(1);
//验证是否被调用2次
verify(list,times(2)).add(2);
//验证是否被调用3次
verify(list,times(3)).add(3);
//验证是否从未被调用过
verify(list,never()).add(4);
//验证至少调用一次
verify(list,atLeastOnce()).add(1);
//验证至少调用2次
verify(list,atLeast(2)).add(2);
//验证至多调用3次
verify(list,atMost(3)).add(3);
</span>}
5、模拟方法体抛出异常
@Test(expected = RuntimeException.class)
public void doThrow_when(){
List list = mock(List.class);
doThrow(new RuntimeException()).when(list).add(1);
list.add(1);
}
6、验证执行顺序
@Test
public void verification_in_order(){
List list = mock(List.class);
List list2 = mock(List.class);
list.add(1);
list2.add("hello");
list.add(2);
list2.add("world");
//将需要排序的mock对象放入InOrder
InOrder inOrder = inOrder(list,list2);
//下面的代码不能颠倒顺序,验证执行顺序
inOrder.verify(list).add(1);
inOrder.verify(list2).add("hello");
inOrder.verify(list).add(2);
inOrder.verify(list2).add("world");
}
7、确保模拟对象上无互动发生
@Test
public void verify_interaction(){
List list = mock(List.class);
List list2 = mock(List.class);
List list3 = mock(List.class);
list.add(1);
verify(list).add(1);
verify(list,never()).add(2);
//验证零互动行为
verifyZeroInteractions(list2,list3);
}
后续还有....
Mockito框架入门教程(一)的更多相关文章
- Mockito框架入门教程(二)
接上一篇,继续学习其它的.... 8.找出冗余的互动(即未被验证到的) @Test(expected = NoInteractionsWanted.class) public void find_re ...
- CodeIgniter框架入门教程——第一课 Hello World!
本文转载自:http://www.softeng.cn/?p=45 今天开始,我将在这里连载由我自己编写的<CodeIgniter框架入门教程>,首先,这篇教程的读着应该是有PHP基础的编 ...
- Java - Struts框架教程 Hibernate框架教程 Spring框架入门教程(新版) sping mvc spring boot spring cloud Mybatis
https://www.zhihu.com/question/21142149 http://how2j.cn/k/hibernate/hibernate-tutorial/31.html?tid=6 ...
- Go-Micro框架入门教程(一)---框架结构
Go语言微服务系列文章,使用golang实现微服务,这里选用的是go-micro框架,本文主要是对该框架的一个架构简单介绍. 1. 概述 go-micro是go语言下的一个很好的微服务框架. 1.服务 ...
- scrapy爬虫框架入门教程
scrapy安装请参考:安装指南. 我们将使用开放目录项目(dmoz)作为抓取的例子. 这篇入门教程将引导你完成如下任务: 创建一个新的Scrapy项目 定义提取的Item 写一个Spider用来爬行 ...
- Scrapy 框架 入门教程
Scrapy入门教程 在本篇教程中,我已经安装好Scrapy 本篇教程中将带您完成下列任务: 创建一个Scrapy项目 定义提取的Item 编写爬取网站的 spider 并提取 Item 编写 Ite ...
- Java Mybatis 框架入门教程
一.Mybatis介绍 MyBatis是一款一流的支持自定义SQL.存储过程和高级映射的持久化框架.MyBatis几乎消除了所有的JDBC代码,也基本不需要手工去 设置参数和获取检索结果.MyBati ...
- CodeIgniter框架入门教程——第三课 URL及ajax
本文转载自:http://www.softeng.cn/?p=74 这节课讲一下CI框架的路由规则,以及如何在CI框架下实现ajax功能. 首先,先介绍CI框架的路由规则,因为CI框架是在PHP的基础 ...
- java之struts框架入门教程
本教程主要讲述struts的简单入门操作 使用的是myeclipse工具 1.创建web项目 2.复制struts必要的jar包到 WebRoot/WEB-INF/lib 下 jar包列表如下: as ...
随机推荐
- js 对日期处理
// 对Date的扩展,将 Date 转化为指定格式的String // 月(M).日(d).小时(h).分(m).秒(s).季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占 ...
- Zookeeper 客户端命令
- PowerShell-自定义函数(五)-参数互斥:ParameterSetName
转自:https://blog.51cto.com/38088444/1920978 这一篇我们来讲一下参数的互斥,何谓参数互斥呢.用九胖风格的话说就是互怼,有我没你,有你没我. 例如我们为一个Pin ...
- 【php】记录一次生产环境bug的调试
参考链接: [php调试利器 -- xdebug]https://www.cnblogs.com/anyeshe/p/5746404.html [PHP 后端调试输出方法(笨办法)]https://b ...
- centos7之rsync+serrsync
Rsync+Inotify-tools与Rsync+sersync这两种架构有什么区别 1.Rsync+Inotify-tools(1):Inotify-tools只能记录下被监听的目录发生了变化(包 ...
- JarvisOJ Misc shell流量分析
分析一下shell流量,得到flag 看着一大推的数据记录头都大了,并没有什么wireshark的使用经验,开始胡搞 首先用notepad++打开,搜索flag字样找到了一个类似于python脚本的东 ...
- 爬虫免登录进入github
import requests import re ret = requests.get('https://github.com/login') print(ret.headers) cookies ...
- Eclipse maven hadoop -- java.io.IOException: No FileSystem for scheme: hdfs
2019-01-10 概述 今天在Windows系统下新安装了Eclipse和maven的环境,想利用Maven构建一个Hadoop程序的,结果却发现程序运行时一直报 “No FileSystem f ...
- Euler Circuit UVA - 10735(混合图输出路径)
就是求混合图是否存在欧拉回路 如果存在则输出一组路径 (我就说嘛 咱的代码怎么可能错.....最后的输出格式竟然w了一天 我都没发现) 解析: 对于无向边定向建边放到网络流图中add(u, v, 1) ...
- Thinkphp5.1 ORM UML
Thinkphp5.1 ORM UML think-orm