PowerMockito使用详解
一、PowerMock概述
现如今比较流行的Mock工具如jMock,EasyMock,Mockito等都有一个共同的缺点:不能mock静态、final、私有方法等。而PowerMock能够完美的弥补以上三个Mock工具的不足。
PowerMock是一个扩展了其它如EasyMock等mock框架的、功能更加强大的框架。PowerMock使用一个自定义类加载器和字节码操作来模拟静态方法,构造函数,final类和方法,私有方法,去除静态初始化器等等。通过使用自定义的类加载器,简化采用的IDE或持续集成服务器不需要做任何改变。熟悉PowerMock支持的mock框架的开发人员会发现PowerMock很容易使用,因为对于静态方法和构造器来说,整个的期望API是一样的。PowerMock旨在用少量的方法和注解扩展现有的API来实现额外的功能。目前PowerMock支持EasyMock和Mockito。
二、PowerMock入门
PowerMock有两个重要的注解:
–@RunWith(PowerMockRunner.class)
–@PrepareForTest( { YourClassWithEgStaticMethod.class })
如果你的测试用例里没有使用注解@PrepareForTest,那么可以不用加注解@RunWith(PowerMockRunner.class),反之亦然。当你需要使用PowerMock强大功能(Mock静态、final、私有方法等)的时候,就需要加注解@PrepareForTest。
三、PowerMock基本用法
(1) 普通Mock: Mock参数传递的对象
//测试目标代码:
public boolean callArgumentInstance(File file) {
return file.exists();
} //测试用例代码:
@Test
public void testCallArgumentInstance() {
File file = PowerMockito.mock(File.class);
Source underTest = new Source();
PowerMockito.when(file.exists()).thenReturn(true);
Assert.assertTrue(underTest.callArgumentInstance(file));
}
说明:普通Mock不需要加@RunWith和@PrepareForTest注解。
(2) Mock方法内部new出来的对象
//测试目标代码:
public boolean callInternalInstance(String path) {
File file = new File(path);
return file.exists();
} //测试用例代码:
@Test
@PrepareForTest(Source.class)
public void testCallInternalInstance() throws Exception
{
File file = PowerMockito.mock(File.class);
Source underTest = new Source();
PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file);
PowerMockito.when(file.exists()).thenReturn(true);
Assert.assertTrue(underTest.callInternalInstance("bbb"));
}
说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。
(3) Mock普通对象的final方法
//测试目标代码:
public class Source {
public boolean callFinalMethod(SourceDepend refer) {
return refer.isAlive();
}
}
public class SourceDepend {
public final boolean isAlive() {
return false;
}
} //测试用例代码:
@Test
@PrepareForTest(SourceDepend.class)
public void testCallFinalMethod()
{
SourceDepend depencency = PowerMockito.mock(SourceDepend.class);
Source underTest = new Source();
PowerMockito.when(depencency.isAlive()).thenReturn(true);
Assert.assertTrue(underTest.callFinalMethod(depencency));
}
说明: 当需要mock final方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是final方法所在的类。
(4) Mock普通类的静态方法
//测试目标代码:
public boolean callStaticMethod() {
return SourceDepend.isExist();
}
public static boolean isExist()
{
return false;
} //测试用例代码:
@Test
@PrepareForTest(SourceDepend.class)
public void testCallStaticMethod() {
Source underTest = new Source();
PowerMockito.mockStatic(SourceDepend.class);
PowerMockito.when(SourceDepend.isExist()).thenReturn(true);
Assert.assertTrue(underTest.callStaticMethod());
}
说明:当需要mock静态方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是静态方法所在的类。
(5) Mock 私有方法
//测试目标代码:
public boolean callPrivateMethod() {
return isExist();
} private boolean isExist() {
return false;
} //测试用例代码:
@Test
@PrepareForTest(Source.class)
public void testCallPrivateMethod() throws Exception
{
Source underTest = PowerMockito.mock(Source.class);
PowerMockito.when(underTest.callPrivateMethod()).thenCallRealMethod();
PowerMockito.when(underTest, "isExist").thenReturn(true);
Assert.assertTrue(underTest.callPrivateMethod());
}
说明:和Mock普通方法一样,只是需要加注解@PrepareForTest(ClassUnderTest.class),注解里写的类是私有方法所在的类。
(6) Mock系统类的静态和final方法
//测试目标代码:
public boolean callSystemFinalMethod(String str)
{
return str.isEmpty();
} public String callSystemStaticMethod(String str)
{
return System.getProperty(str);
} //测试用例代码:
@Test
@PrepareForTest(Source.class)
public void testCallSystemStaticMethod()
{
Source underTest = new Source();
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb");
Assert.assertEquals("bbb", underTest.callSystemStaticMethod("aaa"));
}
说明:和Mock普通对象的静态方法、final方法一样,只不过注解@PrepareForTest里写的类不一样 ,注解里写的类是需要调用系统方法所在的类。
四、无所不能的PowerMock
(1) 验证静态方法:
PowerMockito.verifyStatic();
Static.firstStaticMethod(param);
(2) 扩展验证:
PowerMockito.verifyStatic(Mockito.times(2)); // 被调用2次
Static.thirdStaticMethod(Mockito.anyInt());
// 以任何整数值被调用
(3) 更多的Mock方法
http://code.google.com/p/powermock/wiki/MockitoUsage13
五、PowerMock简单实现原理
当某个测试方法被注解@PrepareForTest标注以后,在运行测试用例时,会创建一个新的org.powermock.core.classloader.MockClassLoader实例,然后加载该测试用例使用到的类(系统类除外)。
PowerMock会根据你的mock要求,去修改写在注解@PrepareForTest里的class文件(当前测试类会自动加入注解中),以满足特殊的mock需求。例如:去除final方法的final标识,在静态方法的最前面加入自己的虚拟实现等。
如果需要mock的是系统类的final方法和静态方法,PowerMock不会直接修改系统类的class文件,而是修改调用系统类的class文件,以满足mock需求。
PowerMockito使用详解的更多相关文章
- PowerMockito使用详解(转)
一.为什么要使用Mock工具 在做单元测试的时候,我们会发现我们要测试的方法会引用很多外部依赖的对象,比如:(发送邮件,网络通讯,远程服务, 文件系统等等). 而我们没法控制这些外部依赖的对象,为了解 ...
- Linq之旅:Linq入门详解(Linq to Objects)
示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...
- 架构设计:远程调用服务架构设计及zookeeper技术详解(下篇)
一.下篇开头的废话 终于开写下篇了,这也是我写远程调用框架的第三篇文章,前两篇都被博客园作为[编辑推荐]的文章,很兴奋哦,嘿嘿~~~~,本人是个很臭美的人,一定得要截图为证: 今天是2014年的第一天 ...
- EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解
前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...
- Java 字符串格式化详解
Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...
- Android Notification 详解(一)——基本操作
Android Notification 详解(一)--基本操作 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Notification 文中如有纰 ...
- Android Notification 详解——基本操作
Android Notification 详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 前几天项目中有用到 Android 通知相关的内容,索性把 Android Notificatio ...
- Git初探--笔记整理和Git命令详解
几个重要的概念 首先先明确几个概念: WorkPlace : 工作区 Index: 暂存区 Repository: 本地仓库/版本库 Remote: 远程仓库 当在Remote(如Github)上面c ...
- Drawable实战解析:Android XML shape 标签使用详解(apk瘦身,减少内存好帮手)
Android XML shape 标签使用详解 一个android开发者肯定懂得使用 xml 定义一个 Drawable,比如定义一个 rect 或者 circle 作为一个 View 的背景. ...
随机推荐
- 谈谈Grunt,NPM,Gulp
随着前端工程化的趋势,产生了越来越多的构建工具,而其中比较优秀的就是grunt,npm,gulp,今天我来说说这三者间的区别以及他们的优缺点. 相信一般前端开发者选择构建工具的时候,更多的是看个人习惯 ...
- codechef [snackdown2017 Onsite Final] Minimax
传送门 题目描述 考虑一个 N 行 N 列的网格,行列编号均为 1 ∼ N.每个格子中包含一个整数.记 ri 为第 i 行的最小值,Ci 为第 i 列的最大值.我们称一个网格为好的,当且仅当满足:$$ ...
- 2017年浙江理工大学程序设计竞赛校赛 题解&源码(A.水, D. 简单贪心 ,E.数论,I 暴力)
Problem A: 回文 Time Limit: 1 Sec Memory Limit: 128 MB Submit: 1719 Solved: 528 Description 小王想知道一个字 ...
- BZOJ 1303: [CQOI2009]中位数图【前缀和】
1303: [CQOI2009]中位数图 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 2737 Solved: 1698[Submit][Statu ...
- Centos7搭建Confluence破解版
Confluence破解版 应用环境: Confluence是一个专业的企业知识管理与协同软件,也可以用于构建企业wiki.通过它可以实现团队成员之间的协作和知识共享. 系统及安装软件 centos7 ...
- [国嵌攻略][070-095][Linux编程函数手册]
第1类 时间编程类 1.1 获取日历时间 1.1.1 函数名 time 1.1.2 函数原形 time_t time(time_t *t) 1.1.3 函数功能 返回日历时间 1.1.4 所属头文件 ...
- Spark算子--foreach和foreachPartition
转载请标明出处http://www.cnblogs.com/haozhengfei/p/6776fe93f754daf60d00d2cb509422a1.html foreach和foreachPar ...
- ZooKeeper 分布式共享锁的实现
原创播客,如需转载请注明出处.原文地址:http://www.cnblogs.com/crawl/p/8352919.html ------------------------------------ ...
- 怎么去掉织梦网站首页带的index.html/index.php
方法1. 1)在空间面板里面找到默认首页设置: 我们是需要去掉index.html,这时我们只需要把index.html这个把它移到最顶级去就行,然后点击确定,在打开网站刷新下,就基本可以解决了! 其 ...
- Java数据结构和算法(十三)——哈希表
Hash表也称散列表,也有直接译作哈希表,Hash表是一种根据关键字值(key - value)而直接进行访问的数据结构.它基于数组,通过把关键字映射到数组的某个下标来加快查找速度,但是又和数组.链表 ...