网络上大部分是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工具如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) { |
测试用例代码:
02 |
public void testCallArgumentInstance() { |
04 |
File file = PowerMockito.mock(File.class); |
06 |
ClassUnderTest underTest = new ClassUnderTest(); |
08 |
PowerMockito.when(file.exists()).thenReturn(true); |
10 |
Assert.assertTrue(underTest.callArgumentInstance(file)); |
说明:普通Mock不需要加@RunWith和@PrepareForTest注解。
(2) Mock方法内部new出来的对象
测试目标代码:
01 |
public class ClassUnderTest { |
03 |
public boolean callInternalInstance(String path) { |
05 |
File file = new File(path); |
测试用例代码:
01 |
@RunWith(PowerMockRunner.class) |
02 |
public class TestClassUnderTest { |
05 |
@PrepareForTest(ClassUnderTest.class) |
06 |
public void testCallInternalInstance() throws Exception { |
08 |
File file = PowerMockito.mock(File.class); |
10 |
ClassUnderTest underTest = new ClassUnderTest(); |
12 |
PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); |
14 |
PowerMockito.when(file.exists()).thenReturn(true); |
16 |
Assert.assertTrue(underTest.callInternalInstance("bbb")); |
说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。
(3) Mock普通对象的final方法
测试目标代码:
1 |
public class ClassUnderTest { |
3 |
public boolean callFinalMethod(ClassDependency refer) { |
5 |
return refer.isAlive(); |
01 |
public class ClassDependency { |
03 |
public final boolean isAlive() { |
测试用例代码:
01 |
@RunWith(PowerMockRunner.class) |
02 |
public class TestClassUnderTest { |
05 |
@PrepareForTest(ClassDependency.class) |
06 |
public void testCallFinalMethod() { |
08 |
ClassDependency depencency = PowerMockito.mock(ClassDependency.class); |
10 |
ClassUnderTest underTest = new ClassUnderTest(); |
12 |
PowerMockito.when(depencency.isAlive()).thenReturn(true); |
14 |
Assert.assertTrue(underTest.callFinalMethod(depencency)); |
说明: 当需要mock final方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是final方法所在的类。
(4) Mock普通类的静态方法
测试目标代码:
1 |
public class ClassUnderTest { |
3 |
public boolean callStaticMethod() { |
5 |
return ClassDependency.isExist(); |
01 |
public class ClassDependency { |
03 |
public static boolean isExist() { |
测试用例代码:
01 |
@RunWith(PowerMockRunner.class) |
02 |
public class TestClassUnderTest { |
05 |
@PrepareForTest(ClassDependency.class) |
06 |
public void testCallStaticMethod() { |
08 |
ClassUnderTest underTest = new ClassUnderTest(); |
10 |
PowerMockito.mockStatic(ClassDependency.class); |
12 |
PowerMockito.when(ClassDependency.isExist()).thenReturn(true); |
14 |
Assert.assertTrue(underTest.callStaticMethod()); |
说明:当需要mock静态方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是静态方法所在的类。
(5) Mock 私有方法
测试目标代码:
01 |
public class ClassUnderTest { |
03 |
public boolean callPrivateMethod() { |
09 |
private boolean isExist() { |
测试用例代码:
01 |
@RunWith(PowerMockRunner.class) |
02 |
public class TestClassUnderTest { |
05 |
@PrepareForTest(ClassUnderTest.class) |
06 |
public void testCallPrivateMethod() throws Exception { |
08 |
ClassUnderTest underTest = PowerMockito.mock(ClassUnderTest.class); |
10 |
PowerMockito.when(underTest.callPrivateMethod()).thenCallRealMethod(); |
12 |
PowerMockito.when(underTest, "isExist").thenReturn(true); |
14 |
Assert.assertTrue(underTest.callPrivateMethod()); |
说明:和Mock普通方法一样,只是需要加注解@PrepareForTest(ClassUnderTest.class),注解里写的类是私有方法所在的类。
(6) Mock系统类的静态和final方法
测试目标代码:
01 |
public class ClassUnderTest { |
03 |
public boolean callSystemFinalMethod(String str) { |
09 |
public String callSystemStaticMethod(String str) { |
11 |
return System.getProperty(str); |
测试用例代码:
01 |
@RunWith(PowerMockRunner.class) |
02 |
public class TestClassUnderTest { |
05 |
@PrepareForTest(ClassUnderTest.class) |
06 |
public void testCallSystemStaticMethod() { |
08 |
ClassUnderTest underTest = new ClassUnderTest(); |
10 |
PowerMockito.mockStatic(System.class); |
12 |
PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb"); |
14 |
Assert.assertEquals("bbb", underTest.callJDKStaticMethod("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需求。
楼主代码:
package com.ericsson.csp.cst.admin.util;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ws.rs.core.Response;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.ericsson.csp.cst.admin.dao.entity.ResponseResult;
import com.ericsson.csp.cst.admin.dao.entity.Syssubp;
import com.ericsson.csp.cst.admin.service.SubscribeService;
import com.ericsson.csp.cst.admin.service.SyssubpService;
@RunWith(PowerMockRunner.class)
public class SubscribeUtilTest{
private Syssubp disp;
private Syssubp fromdisp;
private Syssubp nonSubscribedsubp;
private Syssubp subscribedsubp;
private SubscribeService subscribeService;
private SyssubpService syssubpService;
private SubscribeUtil subscribeUtil;
@Before
public void init() throws Exception{
disp=fillInsubp();
fromdisp=dispsubp();
nonSubscribedsubp=getNonSubscribedLocalsubp();
subscribedsubp=getSubscribedLocalsubp();
syssubpService=PowerMockito.mock(SyssubpService.class);
List<Syssubp> emptyLocalList=new ArrayList<Syssubp>();
List<Syssubp> nonEmptyLocalList=new ArrayList<Syssubp>();
nonEmptyLocalList.add(nonSubscribedsubp);
PowerMockito.doReturn(nonEmptyLocalList).when(syssubpService,"query");
PowerMockito.doNothing().when(syssubpService,"update",Mockito.any(Syssubp.class));
PowerMockito.doNothing().when(syssubpService,"save",Mockito.any(Syssubp.class));
PowerMockito.doNothing().when(syssubpService,"deleteById",Mockito.anyInt());
subscribeService=PowerMockito.mock(SubscribeService.class);
PowerMockito.doReturn(Response.status(200).type(new String()).entity("a string").build()).when(subscribeService,"subscribe",Mockito.any(Syssubp.class));
PowerMockito.doReturn(Response.status(200).type(new String()).entity("a string").build()).when(subscribeService,"deletesubp",Mockito.anyInt());
PowerMockito.when(subscribeService,"getAllsubps").thenReturn(Response.status(200).type(new String()).entity("a string").build());
subscribeUtil=PowerMockito.spy(new SubscribeUtil());
subscribeUtil.setSubscribeService(subscribeService);
subscribeUtil.setsubpService(syssubpService);
}
@Test
@PrepareForTest(SubscribeUtil.class)
public void testSubscribe() throws Exception {
String skip_createResponseResultByResponse="createResponseResultByResponse";
String skip_createsubpBydispResponse="createsubpBydispResponse";
ResponseResult result=new ResponseResult();
result.setStatus(200);
PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
PowerMockito.doReturn(fromdisp).when(subscribeUtil, skip_createsubpBydispResponse, Mockito.any(ResponseResult.class));
ResponseResult resp=subscribeUtil.subscribe(nonSubscribedsubp);
assertEquals(200, resp.getStatus());
}
@Test
public void testUpdatesubpLocally() throws JsonGenerationException, JsonMappingException, IOException{
subscribeUtil.updatesubp(nonSubscribedsubp);
}
@Test
@PrepareForTest(SubscribeUtil.class)
public void testUpdatesubpdisply() throws Exception{
ResponseResult result=new ResponseResult();
result.setStatus(200);
String skip_createResponseResultByResponse="createResponseResultByResponse";
PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
String skip_createsubpBydispResponse="createsubpBydispResponse";
PowerMockito.doReturn(fromdisp).when(subscribeUtil, skip_createsubpBydispResponse, Mockito.any(ResponseResult.class));
subscribeUtil.updatesubp(subscribedsubp);
}
@Test
public void testDeletesubpLocally() throws Exception{
PowerMockito.doReturn(nonSubscribedsubp).when(syssubpService,"queryById",Mockito.anyInt());
subscribeUtil.deletesubp(100);
}
@Test
@PrepareForTest(SubscribeUtil.class)
public void testDeletesubpdisply() throws Exception{
ResponseResult result=new ResponseResult();
result.setStatus(200);
PowerMockito.doReturn(subscribedsubp).when(syssubpService,"queryById",Mockito.anyInt());
String skip_createResponseResultByResponse="createResponseResultByResponse";
PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
subscribeUtil.deletesubp(100);
}
@Test
@PrepareForTest({JacksonUtil.class,SubscribeUtil.class})
public void testSyncdispWhenLocalNonEmpty() throws Exception{
ResponseResult result=new ResponseResult();
result.setStatus(200);
String skip_createResponseResultByResponse="createResponseResultByResponse";
PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
List<Syssubp> dispList=new ArrayList<Syssubp>();
dispList.add(fromdisp);
dispList.add(fromdisp);
dispList.add(fromdisp);
PowerMockito.mockStatic(JacksonUtil.class);
PowerMockito.when(JacksonUtil.getListByTargetClass(Mockito.anyString(), Mockito.eq(Syssubp.class))).thenReturn(dispList);
subscribeUtil.syncSubcriptionWithdisp();
}
@Test
@PrepareForTest({JacksonUtil.class,SubscribeUtil.class})
public void testSyncdispWhenLocalEmpty() throws Exception{
ResponseResult result=new ResponseResult();
result.setStatus(200);
String skip_createResponseResultByResponse="createResponseResultByResponse";
PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
List<Syssubp> dispList=new ArrayList<Syssubp>();
dispList.add(fromdisp);
dispList.add(fromdisp);
dispList.add(fromdisp);
PowerMockito.mockStatic(JacksonUtil.class);
PowerMockito.when(JacksonUtil.getListByTargetClass(Mockito.anyString(), Mockito.eq(Syssubp.class))).thenReturn(dispList);
List<Syssubp> emptyLocalList=new ArrayList<Syssubp>();
PowerMockito.doReturn(emptyLocalList).when(syssubpService,"query");
subscribeUtil.syncSubcriptionWithdisp();
}
private Syssubp fillInsubp() {
Syssubp syssubp=new Syssubp();
syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
syssubp.setTopicServiceId("adade");
syssubp.setEnableTransformation(true);
syssubp.setUsername("");
syssubp.setPassword("");
return syssubp;
}
private Syssubp getNonSubscribedLocalsubp() {
Syssubp syssubp=new Syssubp();
syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
syssubp.setTopicServiceId("adade");
syssubp.setEnableTransformation(true);
syssubp.setUsername("");
syssubp.setPassword("");
syssubp.setApp_name("app");
syssubp.setCreate_time(new Date());
syssubp.setId(100);
return syssubp;
}
private Syssubp getSubscribedLocalsubp() {
Syssubp syssubp=new Syssubp();
syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
syssubp.setTopicServiceId("adade");
syssubp.setEnableTransformation(true);
syssubp.setUsername("");
syssubp.setPassword("");
syssubp.setApp_name("app");
syssubp.setCreate_time(new Date());
syssubp.setId(100);
syssubp.setStatus(true);
syssubp.setUpdate_time(new Date());
syssubp.setsubpId(100);
return syssubp;
}
private Syssubp dispsubp() {
Syssubp syssubp=new Syssubp();
syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
syssubp.setTopicServiceId("adade");
syssubp.setEnableTransformation(true);
syssubp.setUsername("");
syssubp.setPassword("");
syssubp.setsubpId(100);
return syssubp;
}
}
- PowerMock用法[转]
转:http://agiledon.github.io/blog/2013/11/21/play-trick-with-powermock/ 当我们面对一个遗留系统时,常见的问题是没有测试.正如Mic ...
- powerMock比easyMock和Mockito更强大(转)
powerMock是基于easyMock或Mockito扩展出来的增强版本,所以powerMock分两种类型,如果你习惯于使用easyMock的,那你就下载基于easyMock的powerMock,反 ...
- PowerMockito使用详解(转)
一.为什么要使用Mock工具 在做单元测试的时候,我们会发现我们要测试的方法会引用很多外部依赖的对象,比如:(发送邮件,网络通讯,远程服务, 文件系统等等). 而我们没法控制这些外部依赖的对象,为了解 ...
- PowerMockito使用详解
一.PowerMock概述 现如今比较流行的Mock工具如jMock,EasyMock,Mockito等都有一个共同的缺点:不能mock静态.final.私有方法等.而PowerMock能够完美的弥补 ...
- mock测试之powermock
由于公司框架依赖别的模块, 导致我们开发老是需要跟着他们的脚步, 所以我的上级领导提出这个方案说直接跳过他们,我们自己在本地测试,然后就找了它, 导入相关jar <dependency> ...
- 使用PowerMockito和Mockito进行模拟测试,包括静态方法测试,私有方法测试等,以及方法执行的坑或者模拟不成功解决
依赖:这个很重要,不同版本用法也有点区别: <dependency> <groupId>org.mockito</groupId> <artifactId&g ...
- PowerMock介绍
一.为什么要使用Mock工具 在做单元测试的时候,我们会发现我们要测试的方法会引用很多外部依赖的对象,比如:(发送邮件,网络通讯,远程服务, 文件系统等等). 而我们没法控制这些外部依赖的对象,为了解 ...
- PowerMock单元测试
在Java程序的单元测试中常用的mock工具有Mockito和EasyMock.但是这两种mock工具都无法实现对静态.final.私有方法或类的mock.因此有了功能强大的PowerMock工具.P ...
- PowerMock学习之PoweMock的入门(二)
前言 在上一篇<PowerMock学习之PoweMock的入门(一)>文章中,已经简单提及一些关于powermock的用法,但是入门还未完,我还要坚持把它学习并坚持更新到博客中. Mock ...
随机推荐
- 用Swift重写公司OC项目(Day1)--程序的AppIcon与LaunchImage如何设置
公司之前的APP呢经过了两次重写,都是使用OC由本人独立开发的,不过这些东西我都不好意思说是自己写的,真心的一个字:丑!!! 客观原因来说主要是公司要的特别急,而且注重的是功能而非效果,公司的美工之前 ...
- Node.js 学习(六)Node.js EventEmitter
Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队列. Node.js里面的许多对象都会分发事件:一个net.Server对象会在每次有新连接时分发一个事件, 一个fs.read ...
- Netsharp快速入门(之4) 基础档案(之C 实体建模 计量单位、商品、往来单位)
作者:秋时 杨昶 时间:2014-02-15 转载须说明出处 3.3.2 基础档案建模 1.在基础档案项目,右击,选择新建包, 2.录入包的名称,录入名称.完成后点确定 3.3.2.1 计量 ...
- C语言面向对象风格编程
前言 本文略谈C面向对象风格编程,如何使用过程式语言去模拟面向对象的特性?C面向对象的方式和形式很多,不一而足,本文的代码形式是模拟部分C++面向对象关键词并赋予其特性,这种方式对于初级程序员比较好理 ...
- SSIS 控制流和数据流(转)
理解控制流和数据流的一个入口是看他们如何运行的.一个控制流任务是一个最小的执行单位,它的运行结果有成功,失 败,和完成,在运行它的下一个任务之前必须得到这些结果.在数据流任务中,转换时最基本的元素.一 ...
- 使用AzCopy跨账户迁移blob
昨天北美紧急通知要停掉几个开发和测试的订阅,当天必须完成,因为事情比较多,搞得有点我措手不及,但是唯一的遗憾是Azure VM. 因为在上面做了很多东西,很多资料和环境都是做好的,如果被删除掉实在可惜 ...
- 老陈 WPF
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...
- 【CentOS】Eclipse插件egit使用
1.简介 2.安装 3.配置 4.使用 5.补充说明 参考资料: http://yufenfei.iteye.com/blog/1750124 1.简介 EGit就是一款Eclips ...
- UVA 10078 The Art Gallery
Problem: Century Arts has hundreds of art galleries scattered all around the country and you are hir ...
- 玩具装箱 bzoj1010 斜率优化
斜率优化的题好像都是这样的方程:左边关于j,k的一个(...)/(...)的式子,右边是个只与i有关的可算的数字: 然后把它放到二维坐标轴上,用单调队列维护一个凸壳,O(n)的复杂度: 这道题但是我发 ...