一、为什么要使用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需求。

PowerMock介绍的更多相关文章

  1. mock测试之powermock

    由于公司框架依赖别的模块, 导致我们开发老是需要跟着他们的脚步, 所以我的上级领导提出这个方案说直接跳过他们,我们自己在本地测试,然后就找了它, 导入相关jar <dependency> ...

  2. 简单介绍如何使用PowerMock和Mockito来mock 1. 构造函数 2. 静态函数 3. 枚举实现的单例 4. 选择参数值做为函数的返回值(转)

    本文将简单介绍如何使用PowerMock和Mockito来mock1. 构造函数2. 静态函数3. 枚举实现的单例4. 选择参数值做为函数的返回值5. 在调用mock出来的方法中,改变方法参数的值 一 ...

  3. PowerMock 简介--转载

    原文地址:https://www.ibm.com/developerworks/cn/java/j-lo-powermock/ EasyMock 以及 Mockito 都因为可以极大地简化单元测试的书 ...

  4. 使用MRUnit,Mockito和PowerMock进行Hadoop MapReduce作业的单元测试

    0.preliminary 环境搭建 Setup development environment Download the latest version of MRUnit jar from Apac ...

  5. 单元测试系列:Mock工具Jmockit使用介绍

    更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 原文链接:http://www.cnblogs.com/zishi/p/6760272.html Mock工具Jm ...

  6. PowerMock单元测试

    在Java程序的单元测试中常用的mock工具有Mockito和EasyMock.但是这两种mock工具都无法实现对静态.final.私有方法或类的mock.因此有了功能强大的PowerMock工具.P ...

  7. PowerMock简单使用

    网上有很多PowerMock的介绍,此处就不再罗列 下面给出一些资源地址以及几篇案例 mockito资源: (1)源码:https://github.com/mockito/mockito power ...

  8. PowerMock

    EasyMock 以及 Mockito 都因为可以极大地简化单元测试的书写过程而被许多人应用在自己的工作中,但是这 2 种 Mock 工具都不可以实现对静态函数.构造函数.私有函数.Final 函数以 ...

  9. Mockito 库、powermock扩展

    转载:http://blog.csdn.net/kittyboy0001/article/details/18709685 Mockito 简介 Mockito 是目前 java 单测中使用比较流行的 ...

随机推荐

  1. 磁盘满了MySQL会做什么?

    最近遇到一个故障和磁盘满有关系,并且同事也发现经常有磁盘满导致操作hang住无响应的情况,于是抽时间研究了一下这2种情况. 一.磁盘满了之后MySQL会做什么? 我们看下官方的说法 When a di ...

  2. SpringMVC怎么获取前台传来的数组

    var tollerlist = new Array(); for(var k in objToller){ tollerlist.push(k); } $.ajax({ type:"pos ...

  3. 免费的Bootstrap管理后台模板集合

    Free Bootstrap Admin Templates for Designers 1. Admin Lite AdminLTE - 是一个完全响应式管理模板.基于Bootstrap3的框架.高 ...

  4. 深入理解 Java中的 流 (Stream)

    首先,流是什么? 流是个抽象的概念.是对输入输出设备的抽象,Java程序中,对于数据的输入/输出操作都是以"流"的方式进行.设备能够是文件,网络,内存等. 流具有方向性,至于是输入 ...

  5. DI容器Ninject在管理接口和实现、基类和派生类并实现依赖注入方面的实例

    当一个类依赖于另一个具体类的时候,这样很容易形成两者间的"强耦合"关系.我们通常根据具体类抽象出一个接口,然后让类来依赖这个接口,这样就形成了"松耦合"关系,有 ...

  6. spring Annotation 组件注入

    spring 注解的分类 启动spring自己主动扫描功能 <context:component-scan/> 1.@Repository: 它用于将数据訪问层 (DAO 层 ) 的类标识 ...

  7. Spring3数据源的6种配置方法

    在Spring3中,配置DataSource的方法有五种. 第一种:beans.xml <bean id="dataSource" class="org.apach ...

  8. ConcurrentHashMap之实现细节

    ConcurrentHashMap是Java 5中支持高并发.高吞吐量的线程安全HashMap实现.在这之前我对ConcurrentHashMap只有一些肤浅的理解,仅知道它采用了多个锁,大概也足够了 ...

  9. 局部敏感哈希 Kernelized Locality-Sensitive Hashing Page

    Kernelized Locality-Sensitive Hashing Page   Brian Kulis (1) and Kristen Grauman (2)(1) UC Berkeley ...

  10. OpenCV学习(21) Grabcut算法详解

    grab cut算法是graph cut算法的改进.在理解grab cut算之前,应该学习一下graph cut算法的概念及实现方式. 我搜集了一些graph cut资料:http://yunpan. ...