PowerMockito使用详解

PowerMockito使用详解一 为什么要使用 Mock 工具 nbsp nbsp nbsp nbsp 在做单元测试的时候 我们会发现我们要测试的方法会引用很多外部依赖的对象 比如 发送邮件 网络通讯 远程服务 文件系统等等 而我们没法控制这些外部依赖的对象 为了解决这个问题 我们就需要用到 Mock 工具来模拟这些外部依赖的对象 来完成单元测试 nbsp nbsp nbsp nbsp 二 为什么要使用 PowerMock nbsp nbsp nbsp 现如今比较流行的 Mock 工具如 jMo

 一、为什么要使用Mock工具

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

      二、为什么要使用PowerMock

      现如今比较流行的Mock工具如jMock EasyMock 、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需求。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/199595.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月20日 下午12:39
下一篇 2026年3月20日 下午12:39


相关推荐

  • 《欲罢不能:刷屏时代如何摆脱行为上瘾》书摘

    《欲罢不能:刷屏时代如何摆脱行为上瘾》书摘!!!此书大大提高我对这个信息时代的认知,也理解了为什么过去对一些事情那么沉迷。一开始书讲一些物质上瘾,确实不太好看,但是往下看你会感到惊讶。这个信息时代给了我们这代人,太多了获得感,并非获得。这是我最大的感受。然后。具体讲什么内容,谁看谁知道。

    2022年6月23日
    24
  • html5不用reload重置网页,refresh和reload「建议收藏」

    html5不用reload重置网页,refresh和reload「建议收藏」location.refresh和location.reload的区别在什么location.refresh:刷新页面location.reload:重载页面javascript怎么刷新页面,要refresh不要reloadlocation.reload();下面是复制的用js实现的刷新页面的代码,比较全先来看一个简单的例子:下面以三个页面分别命名为frame.html、top.htm…

    2022年7月18日
    26
  • PUCHARM激活码[在线序列号]

    PUCHARM激活码[在线序列号],https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月18日
    44
  • 反射型xss实战演示「建议收藏」

    反射型xss实战演示「建议收藏」我们知道,XSS攻击大致分为三种类型:Persistent型(持久型),Non-persistent(反射型)及Dom-based型。而反射型是最常用,也是使用得最广的一种攻击方式。它通过给别人发送带有恶意脚本代码参数的URL,当URL地址被打开时,特有的恶意代码参数被HTML解析、执行。它的特点是非持久化,必须用户点击带有特定参数的链接才能引起。   今天,通过一个反射型xss的实战演示

    2022年6月11日
    43
  • c语言中求字符串的长度的函数_c语言求最大字符串

    c语言中求字符串的长度的函数_c语言求最大字符串在C语言中求字符串的长度,可以使用sizeof()函数和strlen()函数,后者需要引入string.h(#include<string.h>)因为C语言字符串是以\0结尾表示

    2022年8月4日
    7
  • Qwen Code 新手入门指南

    Qwen Code 新手入门指南

    2026年3月13日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号