一、为什么要使用Mock工具

在做单元测试的时候,我们会发现我们要测试的方法会引用很多外部依赖的对象,比如:(发送邮件,网络通讯,远程服务, 文件系统等等)。 而我们没法控制这些外部依赖的对象,为了解决这个问题,我们就需要用到Mock工具来模拟这些外部依赖的对象,来完成单元测试。

 二、为什么要使用PowerMock

现如今比较流行的Mock工具如jMockEasyMock 、Mockito等都有一个共同的缺点:不能mock静态、final、私有方法等。而PowerMock能够完美的弥补以上三个Mock工具的不足。

三、PowerMock简介

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参数传递的对象

测试目标代码:

1 public boolean callArgumentInstance(File file) {
2  
3      return file.exists();
4  
5 }

测试用例代码:

01 @Test 
02 public void testCallArgumentInstance() {
03   
04     File file = PowerMockito.mock(File.class); 
05  
06     ClassUnderTest underTest = new ClassUnderTest();
07    
08     PowerMockito.when(file.exists()).thenReturn(true);
09   
10     Assert.assertTrue(underTest.callArgumentInstance(file)); 
11 }

说明:普通Mock不需要加@RunWith和@PrepareForTest注解。

(2)  Mock方法内部new出来的对象

测试目标代码:

01 public class ClassUnderTest {
02  
03     public boolean callInternalInstance(String path) { 
04  
05         File file = new File(path); 
06  
07         return file.exists(); 
08  
09     
10 }

测试用例代码:

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04     @Test 
05     @PrepareForTest(ClassUnderTest.class
06     public void testCallInternalInstance() throws Exception { 
07  
08         File file = PowerMockito.mock(File.class); 
09  
10         ClassUnderTest underTest = new ClassUnderTest(); 
11  
12         PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); 
13          
14         PowerMockito.when(file.exists()).thenReturn(true); 
15  
16         Assert.assertTrue(underTest.callInternalInstance("bbb")); 
17     
18 }

说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。

(3) Mock普通对象的final方法

测试目标代码:

1 public class ClassUnderTest {
2  
3     public boolean callFinalMethod(ClassDependency refer) { 
4  
5         return refer.isAlive(); 
6  
7     
8 }
01 public class ClassDependency {
02      
03     public final boolean isAlive() {
04  
05         // do something 
06  
07         return false
08  
09     
10 }

测试用例代码:

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04     @Test 
05     @PrepareForTest(ClassDependency.class
06     public void testCallFinalMethod() {
07  
08         ClassDependency depencency =  PowerMockito.mock(ClassDependency.class);
09   
10         ClassUnderTest underTest = new ClassUnderTest();
11   
12         PowerMockito.when(depencency.isAlive()).thenReturn(true);
13   
14         Assert.assertTrue(underTest.callFinalMethod(depencency));
15   
16     }
17 }

说明: 当需要mock final方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是final方法所在的类。

(4) Mock普通类的静态方法

测试目标代码:

1 public class ClassUnderTest {
2  
3     public boolean callStaticMethod() {
4   
5         return ClassDependency.isExist(); 
6  
7     }  
8 }
01 public class ClassDependency {
02     
03     public static boolean isExist() {
04  
05         // do something 
06  
07         return false
08  
09     
10 }

测试用例代码:

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04     @Test 
05     @PrepareForTest(ClassDependency.class
06     public void testCallStaticMethod() {
07   
08         ClassUnderTest underTest = new ClassUnderTest();
09   
10         PowerMockito.mockStatic(ClassDependency.class); 
11  
12         PowerMockito.when(ClassDependency.isExist()).thenReturn(true);
13   
14         Assert.assertTrue(underTest.callStaticMethod());
15   
16     }
17 }

说明:当需要mock静态方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是静态方法所在的类。

(5) Mock 私有方法

测试目标代码:

01 public class ClassUnderTest {
02  
03     public boolean callPrivateMethod() { 
04  
05         return isExist(); 
06  
07     }       
08  
09     private boolean isExist() {
10    
11         return false
12  
13     }
14 }

测试用例代码:

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04     @Test 
05     @PrepareForTest(ClassUnderTest.class
06     public void testCallPrivateMethod() throws Exception { 
07  
08        ClassUnderTest underTest = PowerMockito.mock(ClassUnderTest.class); 
09  
10        PowerMockito.when(underTest.callPrivateMethod()).thenCallRealMethod(); 
11  
12        PowerMockito.when(underTest, "isExist").thenReturn(true);
13    
14        Assert.assertTrue(underTest.callPrivateMethod());
15   
16     }
17 }

说明:和Mock普通方法一样,只是需要加注解@PrepareForTest(ClassUnderTest.class),注解里写的类是私有方法所在的类。

(6) Mock系统类的静态和final方法

测试目标代码:

01 public class ClassUnderTest {
02  
03     public boolean callSystemFinalMethod(String str) {
04  
05         return str.isEmpty(); 
06  
07     
08  
09     public String callSystemStaticMethod(String str) {
10   
11         return System.getProperty(str); 
12  
13     }
14 }

测试用例代码:

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04   @Test 
05   @PrepareForTest(ClassUnderTest.class
06   public void testCallSystemStaticMethod() { 
07  
08       ClassUnderTest underTest = new ClassUnderTest(); 
09  
10       PowerMockito.mockStatic(System.class); 
11  
12       PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb");
13    
14       Assert.assertEquals("bbb", underTest.callJDKStaticMethod("aaa")); 
15  
16   
17 }

说明:和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需求。

http://blog.csdn.net/knighttools/article/details/44630975

PowerMockito使用详解(转)的更多相关文章

  1. PowerMockito使用详解

    一.PowerMock概述 现如今比较流行的Mock工具如jMock,EasyMock,Mockito等都有一个共同的缺点:不能mock静态.final.私有方法等.而PowerMock能够完美的弥补 ...

  2. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

  3. 架构设计:远程调用服务架构设计及zookeeper技术详解(下篇)

    一.下篇开头的废话 终于开写下篇了,这也是我写远程调用框架的第三篇文章,前两篇都被博客园作为[编辑推荐]的文章,很兴奋哦,嘿嘿~~~~,本人是个很臭美的人,一定得要截图为证: 今天是2014年的第一天 ...

  4. EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解

    前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...

  5. Java 字符串格式化详解

    Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...

  6. Android Notification 详解(一)——基本操作

    Android Notification 详解(一)--基本操作 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Notification 文中如有纰 ...

  7. Android Notification 详解——基本操作

    Android Notification 详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 前几天项目中有用到 Android 通知相关的内容,索性把 Android Notificatio ...

  8. Git初探--笔记整理和Git命令详解

    几个重要的概念 首先先明确几个概念: WorkPlace : 工作区 Index: 暂存区 Repository: 本地仓库/版本库 Remote: 远程仓库 当在Remote(如Github)上面c ...

  9. Drawable实战解析:Android XML shape 标签使用详解(apk瘦身,减少内存好帮手)

    Android XML shape 标签使用详解   一个android开发者肯定懂得使用 xml 定义一个 Drawable,比如定义一个 rect 或者 circle 作为一个 View 的背景. ...

随机推荐

  1. 高版本jQuery设置checkbox状态注意事项

    jQuery 1.9 以后, 使用 .attr(“checked”, true) 或  attr(“checked”, “checked”) 将无法正确设置 checkbox的状态, 同样的, 使用 ...

  2. Java文件压缩分割(待)

    http://blog.csdn.net/ycg01/article/details/1366648

  3. vb.net版机房收费——助你学会七层架构(一)

    我自己写机房的时候,看非常多高人的博客,各种的借鉴,当初务必的纠结,如今整个机房敲完了,写这篇博客给大家一个总体上的.简单理解的七层,期望大家看完这篇文章之后,不会这个纠结了. 首先大家得看了我的上一 ...

  4. 使用Visual Studio 创建可视Web Part部件

    使用Visual Studio 创建可视Web Part部件 可视Web Part部件是很强大的Web 部件.它提供内置设计器创建你的用户界面. 本文主要解说怎样使用Visual Studio 创建可 ...

  5. java枚举的使用

    定义枚举 public enum YesOrNo { YES("是") , NO("否") ; private String text ; private in ...

  6. 虚拟化技术学习(一)在VMware虚拟机中安装KVM

    近期一直研究虚拟化技术,曾经对VMware虚拟机有一定的了解,近期突发奇想,能不能在VMware虚拟机中再装一个虚拟机呢? 那么问题就来了,首先,你须要一台电脑,vmware软件,(本人的电脑配置渣渣 ...

  7. mysql经常使用的命令

    如何登陆数据库     飞机着陆     mysql -u <username> -p     访问本机数据库     mysql -u <username> -D <d ...

  8. struts2原理分析

    正在使用struts之前,我们必须明白servlet执行.因为不管什么J2EE框架支持servlet的. 和servlet正在运行的进程.简单地说,例如,下面的: 1.server接收请求 2.一个过 ...

  9. Android4.0设置接口变更摘要(四)

    为了与你之前,你已经设置了共享Tab风格和Item实现圆角.希望能给有须要的朋友一点点帮助,今天再和大家分享一下用ViewPager实现设置分页,小米和OPPO就是这种设置,先来看看效果图: wate ...

  10. 阅读:AirBag Boosting Smartphone Resistance to Malware Infection