网络上大部分是powermock 的用法,

PowerMock有两个重要的注解:

–@RunWith(PowerMockRunner.class)

–@PrepareForTest( { YourClassWithEgStaticMethod.class })

但是powermockito @PrepareForTest( { YourClassWithEgStaticMethod.class }) 是在使用时 每个test case 方法中按需添加的。 @RunWith(PowerMockRunner.class)  必须添加到类名头。

摘自:

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

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

楼主代码:

  1. package com.ericsson.csp.cst.admin.util;
  2.  
  3. import static org.junit.Assert.assertEquals;
  4.  
  5. import java.io.IOException;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.List;
  9.  
  10. import javax.ws.rs.core.Response;
  11.  
  12. import org.codehaus.jackson.JsonGenerationException;
  13. import org.codehaus.jackson.map.JsonMappingException;
  14. import org.junit.Before;
  15. import org.junit.Test;
  16. import org.junit.runner.RunWith;
  17. import org.mockito.Mockito;
  18. import org.powermock.api.mockito.PowerMockito;
  19. import org.powermock.core.classloader.annotations.PrepareForTest;
  20. import org.powermock.modules.junit4.PowerMockRunner;
  21.  
  22. import com.ericsson.csp.cst.admin.dao.entity.ResponseResult;
  23. import com.ericsson.csp.cst.admin.dao.entity.Syssubp;
  24. import com.ericsson.csp.cst.admin.service.SubscribeService;
  25. import com.ericsson.csp.cst.admin.service.SyssubpService;
  26.  
  27. @RunWith(PowerMockRunner.class)
  28. public class SubscribeUtilTest{
  29.  
  30. private Syssubp disp;
  31. private Syssubp fromdisp;
  32. private Syssubp nonSubscribedsubp;
  33. private Syssubp subscribedsubp;
  34.  
  35. private SubscribeService subscribeService;
  36.  
  37. private SyssubpService syssubpService;
  38.  
  39. private SubscribeUtil subscribeUtil;
  40.  
  41. @Before
  42. public void init() throws Exception{
  43. disp=fillInsubp();
  44. fromdisp=dispsubp();
  45. nonSubscribedsubp=getNonSubscribedLocalsubp();
  46. subscribedsubp=getSubscribedLocalsubp();
  47.  
  48. syssubpService=PowerMockito.mock(SyssubpService.class);
  49. List<Syssubp> emptyLocalList=new ArrayList<Syssubp>();
  50. List<Syssubp> nonEmptyLocalList=new ArrayList<Syssubp>();
  51. nonEmptyLocalList.add(nonSubscribedsubp);
  52. PowerMockito.doReturn(nonEmptyLocalList).when(syssubpService,"query");
  53. PowerMockito.doNothing().when(syssubpService,"update",Mockito.any(Syssubp.class));
  54. PowerMockito.doNothing().when(syssubpService,"save",Mockito.any(Syssubp.class));
  55. PowerMockito.doNothing().when(syssubpService,"deleteById",Mockito.anyInt());
  56.  
  57. subscribeService=PowerMockito.mock(SubscribeService.class);
  58. PowerMockito.doReturn(Response.status(200).type(new String()).entity("a string").build()).when(subscribeService,"subscribe",Mockito.any(Syssubp.class));
  59. PowerMockito.doReturn(Response.status(200).type(new String()).entity("a string").build()).when(subscribeService,"deletesubp",Mockito.anyInt());
  60. PowerMockito.when(subscribeService,"getAllsubps").thenReturn(Response.status(200).type(new String()).entity("a string").build());
  61.  
  62. subscribeUtil=PowerMockito.spy(new SubscribeUtil());
  63. subscribeUtil.setSubscribeService(subscribeService);
  64. subscribeUtil.setsubpService(syssubpService);
  65. }
  66.  
  67. @Test
  68. @PrepareForTest(SubscribeUtil.class)
  69. public void testSubscribe() throws Exception {
  70.  
  71. String skip_createResponseResultByResponse="createResponseResultByResponse";
  72. String skip_createsubpBydispResponse="createsubpBydispResponse";
  73.  
  74. ResponseResult result=new ResponseResult();
  75. result.setStatus(200);
  76.  
  77. PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
  78. PowerMockito.doReturn(fromdisp).when(subscribeUtil, skip_createsubpBydispResponse, Mockito.any(ResponseResult.class));
  79.  
  80. ResponseResult resp=subscribeUtil.subscribe(nonSubscribedsubp);
  81.  
  82. assertEquals(200, resp.getStatus());
  83.  
  84. }
  85.  
  86. @Test
  87. public void testUpdatesubpLocally() throws JsonGenerationException, JsonMappingException, IOException{
  88.  
  89. subscribeUtil.updatesubp(nonSubscribedsubp);
  90. }
  91.  
  92. @Test
  93. @PrepareForTest(SubscribeUtil.class)
  94. public void testUpdatesubpdisply() throws Exception{
  95.  
  96. ResponseResult result=new ResponseResult();
  97. result.setStatus(200);
  98.  
  99. String skip_createResponseResultByResponse="createResponseResultByResponse";
  100. PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
  101. String skip_createsubpBydispResponse="createsubpBydispResponse";
  102. PowerMockito.doReturn(fromdisp).when(subscribeUtil, skip_createsubpBydispResponse, Mockito.any(ResponseResult.class));
  103.  
  104. subscribeUtil.updatesubp(subscribedsubp);
  105. }
  106.  
  107. @Test
  108. public void testDeletesubpLocally() throws Exception{
  109. PowerMockito.doReturn(nonSubscribedsubp).when(syssubpService,"queryById",Mockito.anyInt());
  110. subscribeUtil.deletesubp(100);
  111. }
  112. @Test
  113. @PrepareForTest(SubscribeUtil.class)
  114. public void testDeletesubpdisply() throws Exception{
  115. ResponseResult result=new ResponseResult();
  116. result.setStatus(200);
  117.  
  118. PowerMockito.doReturn(subscribedsubp).when(syssubpService,"queryById",Mockito.anyInt());
  119. String skip_createResponseResultByResponse="createResponseResultByResponse";
  120. PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
  121.  
  122. subscribeUtil.deletesubp(100);
  123. }
  124.  
  125. @Test
  126. @PrepareForTest({JacksonUtil.class,SubscribeUtil.class})
  127. public void testSyncdispWhenLocalNonEmpty() throws Exception{
  128. ResponseResult result=new ResponseResult();
  129. result.setStatus(200);
  130. String skip_createResponseResultByResponse="createResponseResultByResponse";
  131. PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
  132.  
  133. List<Syssubp> dispList=new ArrayList<Syssubp>();
  134. dispList.add(fromdisp);
  135. dispList.add(fromdisp);
  136. dispList.add(fromdisp);
  137.  
  138. PowerMockito.mockStatic(JacksonUtil.class);
  139. PowerMockito.when(JacksonUtil.getListByTargetClass(Mockito.anyString(), Mockito.eq(Syssubp.class))).thenReturn(dispList);
  140.  
  141. subscribeUtil.syncSubcriptionWithdisp();
  142. }
  143.  
  144. @Test
  145. @PrepareForTest({JacksonUtil.class,SubscribeUtil.class})
  146. public void testSyncdispWhenLocalEmpty() throws Exception{
  147. ResponseResult result=new ResponseResult();
  148. result.setStatus(200);
  149. String skip_createResponseResultByResponse="createResponseResultByResponse";
  150. PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
  151.  
  152. List<Syssubp> dispList=new ArrayList<Syssubp>();
  153. dispList.add(fromdisp);
  154. dispList.add(fromdisp);
  155. dispList.add(fromdisp);
  156.  
  157. PowerMockito.mockStatic(JacksonUtil.class);
  158. PowerMockito.when(JacksonUtil.getListByTargetClass(Mockito.anyString(), Mockito.eq(Syssubp.class))).thenReturn(dispList);
  159.  
  160. List<Syssubp> emptyLocalList=new ArrayList<Syssubp>();
  161. PowerMockito.doReturn(emptyLocalList).when(syssubpService,"query");
  162.  
  163. subscribeUtil.syncSubcriptionWithdisp();
  164. }
  165.  
  166. private Syssubp fillInsubp() {
  167. Syssubp syssubp=new Syssubp();
  168. syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
  169. syssubp.setTopicServiceId("adade");
  170. syssubp.setEnableTransformation(true);
  171. syssubp.setUsername("");
  172. syssubp.setPassword("");
  173. return syssubp;
  174. }
  175. private Syssubp getNonSubscribedLocalsubp() {
  176. Syssubp syssubp=new Syssubp();
  177. syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
  178. syssubp.setTopicServiceId("adade");
  179. syssubp.setEnableTransformation(true);
  180. syssubp.setUsername("");
  181. syssubp.setPassword("");
  182. syssubp.setApp_name("app");
  183. syssubp.setCreate_time(new Date());
  184. syssubp.setId(100);
  185. return syssubp;
  186. }
  187. private Syssubp getSubscribedLocalsubp() {
  188. Syssubp syssubp=new Syssubp();
  189. syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
  190. syssubp.setTopicServiceId("adade");
  191. syssubp.setEnableTransformation(true);
  192. syssubp.setUsername("");
  193. syssubp.setPassword("");
  194. syssubp.setApp_name("app");
  195. syssubp.setCreate_time(new Date());
  196. syssubp.setId(100);
  197. syssubp.setStatus(true);
  198. syssubp.setUpdate_time(new Date());
  199. syssubp.setsubpId(100);
  200. return syssubp;
  201. }
  202.  
  203. private Syssubp dispsubp() {
  204. Syssubp syssubp=new Syssubp();
  205. syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
  206. syssubp.setTopicServiceId("adade");
  207. syssubp.setEnableTransformation(true);
  208. syssubp.setUsername("");
  209. syssubp.setPassword("");
  210. syssubp.setsubpId(100);
  211. return syssubp;
  212. }
  213. }

PowerMockito(PowerMock用法)的更多相关文章

  1. PowerMock用法[转]

    转:http://agiledon.github.io/blog/2013/11/21/play-trick-with-powermock/ 当我们面对一个遗留系统时,常见的问题是没有测试.正如Mic ...

  2. powerMock比easyMock和Mockito更强大(转)

    powerMock是基于easyMock或Mockito扩展出来的增强版本,所以powerMock分两种类型,如果你习惯于使用easyMock的,那你就下载基于easyMock的powerMock,反 ...

  3. PowerMockito使用详解(转)

    一.为什么要使用Mock工具 在做单元测试的时候,我们会发现我们要测试的方法会引用很多外部依赖的对象,比如:(发送邮件,网络通讯,远程服务, 文件系统等等). 而我们没法控制这些外部依赖的对象,为了解 ...

  4. PowerMockito使用详解

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

  5. mock测试之powermock

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

  6. 使用PowerMockito和Mockito进行模拟测试,包括静态方法测试,私有方法测试等,以及方法执行的坑或者模拟不成功解决

    依赖:这个很重要,不同版本用法也有点区别: <dependency> <groupId>org.mockito</groupId> <artifactId&g ...

  7. PowerMock介绍

    一.为什么要使用Mock工具 在做单元测试的时候,我们会发现我们要测试的方法会引用很多外部依赖的对象,比如:(发送邮件,网络通讯,远程服务, 文件系统等等). 而我们没法控制这些外部依赖的对象,为了解 ...

  8. PowerMock单元测试

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

  9. PowerMock学习之PoweMock的入门(二)

    前言 在上一篇<PowerMock学习之PoweMock的入门(一)>文章中,已经简单提及一些关于powermock的用法,但是入门还未完,我还要坚持把它学习并坚持更新到博客中. Mock ...

随机推荐

  1. require.js的用法

    我采用的是一个非常流行的库require.js. 一.为什么要用require.js? 最早的时候,所有Javascript代码都写在一个文件里面,只要加载这一个文件就够了.后来,代码越来越多,一个文 ...

  2. 发现了一个制作iOS图标的利器

    我制作的第一个Swift Demo已经将近完工,今天的任务便是给它添加图标.不过Xcode中对图标尺寸的要求还真是严苛,若是制作iPhone和iPad通用的应用,总共需要12种尺寸的图标,这对于美工功 ...

  3. 深入浅出TCP/IP簇

    TCP/IP是“transmission Control Protocol/Internet Protocol”的简写,中文译名为传输控制协议/互联网络协议.TCP/IP不是一个协议,而是一个协议簇的 ...

  4. QT实现软件重启

    //重启软件 void MainWindow::on_pushButton_UI_reboot_clicked() { //方式1 需要主函数中事件循环判断 //qApp->exit(773); ...

  5. Valid Palindrome

    leetcode:https://oj.leetcode.com/problems/ 今天A了一个Easy类型的,主要是判断一个字符串是否是回文.东平西凑的还是给弄好了,具体可看下面的要求,或者直接去 ...

  6. Visual Studio 2013 各版本注册码

    Visual Studio Ultimate 2013 KEY(密钥):BWG7X-J98B3-W34RT-33B3R-JVYW9 Visual Studio Premium 2013 KEY(密钥) ...

  7. Codeforces Round #354 (Div. 2) C. Vasya and String

    题目链接: http://codeforces.com/contest/676/problem/C 题解: 把连续的一段压缩成一个数,对新的数组求前缀和,用两个指针从左到右线性扫一遍. 一段值改变一部 ...

  8. BZOJ3874 codevs3361 宅男计划

    AC通道1:http://www.lydsy.com/JudgeOnline/problem.php?id=3874 AC通道2:http://codevs.cn/problem/3361/ [题目分 ...

  9. Nginx的accept_mutex配置分析

    让我们看看accept_mutex的意义:当一个新连接到达时,如果激活了accept_mutex,那么多个Worker将以串行方式来处理,其中有一个Worker会被唤醒,其他的Worker继续保持休眠 ...

  10. C51关键字

    C51 中的关键字 关键字 用途 说明 auto 存储种类说明 用以说明局部变量,缺省值为此 break 程序语句 退出最内层循环 case 程序语句 Switch语句中的选择项 char 数据类型说 ...