PowerMocker 是一个功能逆天的mock 工具。

一,Powermockito 针对方法中new 对象的模拟

// 如何才能mock掉 WeChatConfigUtil 这个类,让 weChatConfigUtil.getMainApploginSwitch();这个方法返回你想要的结果
public void testA(){
WeChatConfigUtil weChatConfigUtil = new WeChatConfigUtil();
weChatConfigUtil.getMainAppLoginSwitch();
}

针对上述情况

package com.ppdai.wechat.sub.business.msgsub;

import com.ppdai.wechat.sub.util.WeChatConfigUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; /**
* Created by huxuhong on 2020/7/2.
*/
//重点,要帮要mock的类(此例为weChatConfigUtil 所在的类TestC,要放到PrepareForTest中即可)
@PrepareForTest(
{ TestB.TestC.class
})
@RunWith(PowerMockRunner.class)
public class TestB {
public TestB(){ }
class TestC{
public void testA(){
WeChatConfigUtil weChatConfigUtil = new WeChatConfigUtil();
Boolean flag = weChatConfigUtil.getMainAppLoginSwitch();
System.out.println("mock结果"+flag);
}
} @Test
public void testTestC(){
TestC testC = new TestC();
WeChatConfigUtil weChatConfigUtil = PowerMockito.mock(WeChatConfigUtil.class);
try {
PowerMockito.whenNew(WeChatConfigUtil.class).withAnyArguments().thenReturn(weChatConfigUtil);
PowerMockito.doReturn(Boolean.TRUE).when(weChatConfigUtil).getMainAppLoginSwitch();
testC.testA();
} catch (Exception e) {
e.printStackTrace();
}
}
}

运行结果

二,如何解决属性中new 对象的模拟

public class TestB {
public TestB(){ }
class TestC{
//如何mock掉属性中new 对象(此例为WechatConfigUtil weChatConfigUtil = new WechatConfigUtil,让 weChatConfigUtil.getUserInfoApiUrl 能获取到指定的值)
WeChatConfigUtil weChatConfigUtil = new WeChatConfigUtil();
public void testA(){
String t = weChatConfigUtil.getUserInfoApiUrl();
System.out.println("mock结果"+t);
}
}

  

针对上述情况

public class TestB {
public TestB(){ }
class TestC{
//如果熟悉修饰为pubilc final static WechatConfigUtil,那么就需要和上面的例子一样要配置@PrepareForTest
WeChatConfigUtil weChatConfigUtil = new WeChatConfigUtil();
public void testA(){
String t = weChatConfigUtil.getUserInfoApiUrl();
System.out.println("mock结果"+t);
}
} @Test
public void testTestC(){
TestC testC = new TestC();
WeChatConfigUtil weChatConfigUtil = PowerMockito.mock(WeChatConfigUtil.class);
try {
Field weChatConfigUtilField = testC.getClass().getDeclaredField("weChatConfigUtil");
weChatConfigUtilField.setAccessible(Boolean.TRUE);
weChatConfigUtilField.set(testC,weChatConfigUtil);
PowerMockito.doReturn("testpc").when(weChatConfigUtil).getUserInfoApiUrl();
testC.testA();
} catch (Exception e) {
e.printStackTrace();
}
} }

  运行结果

三,引入Powermock的时候注意和mockito的版本匹配问题

  Powermock 使用过程中遇到的坑

   ①,使用Powermock mock 静态方法时,提示下面错误

        org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class

处理方式:版本问题,修改为  mockito 2.25.0,powermock 2.0.2,

        issue https://github.com/powermock/powermock/issues/992#ref-commit-3479902

mockito 2.25.0和powermock 2.0.2

Powermockito 针对方法中new 对象的模拟,以及属性中new 对象的模拟的更多相关文章

  1. 将java中Map对象转为有相同属性的类对象(json作为中间转换)

    java中Map对象转为有相同属性的类对象(json作为中间转换) 准备好json转换工具类 public class JsonUtil { private static ObjectMapper o ...

  2. python小知识-__call__和类装饰器的结合使用,数据描述符__get__\__set__\__delete__(描述符类是Python中一种用于储存类属性值的对象)

    class Decorator(): def __init__(self, f): print('run in init......') self.f = f def __call__(self, a ...

  3. JavaScript 中 Object ,Prototype 相关的属性和方法

    span { font-family: 'Consolas'; font-size: 10pt; color: #ffffff; } .sc0 { } .sc2 { color: #c0c0c0; } ...

  4. 两种方法实现用CSS切割图片只取图片中一部分

    切割图片这里不是真正的切割,只是用CSS取图片中的一部分而已,主要有两种方式,一是做为某一元素的背景图片,二是用img元素的属性.下面有个不错的示例,大家可以参考下 切割图片这里不是真正的切割,只是用 ...

  5. 细说JavaScript对象(1):对象的使用和属性

    JavaScript 中的一切都可以视为对象,除了两个特例:null 和 undefined. false.toString(); // 'false' [1, 2, 3].toString(); / ...

  6. class属性中为什会添加非样式的属性值?

    来由 在一些插件中经常看到, 在class属性中出现一些跟样式无关的属性值, 这些值在css样式中没有对应定义, 但是在js中会根据这个值来给dom对象添加特殊的行为, 例如: jquery vali ...

  7. ARC属性中还能使用assign,copy,retain这些关键字吗

    http://blog.sina.com.cn/s/blog_6531b9b80101c6cr.html      很早以前比较弱,网上不知道哪里看了篇博文,留下了ARC属性中不能使用retain关键 ...

  8. C#中??和?分别是什么意思? 在ASP.NET开发中一些单词的标准缩写 C#SESSION丢失问题的解决办法 在C#中INTERFACE与ABSTRACT CLASS的区别 SQL命令语句小技巧 JQUERY判断CHECKBOX是否选中三种方法 JS中!=、==、!==、===的用法和区别 在对象比较中,对象相等和对象一致分别指的是什么?

    C#中??和?分别是什么意思? 在C#中??和?分别是什么意思? 1. 可空类型修饰符(?):引用类型可以使用空引用表示一个不存在的值,而值类型通常不能表示为空.例如:string str=null; ...

  9. 简单模拟实现javascript中的call、apply、bind方法

    目录 引子 隐式丢失 硬绑定 实现及原理分析 总体实现(纯净版/没有注释) 写在最后 引子 读完<你不知道的JavaScript--上卷>中关于this的介绍和深入的章节后,对于this的 ...

随机推荐

  1. non-local denoising methods

    NL-Means算法 在噪声先验为高斯噪声的基础上, 进行non-local的平均,在2005年由Baudes提出,该算法使用自然图像中普遍存在的冗余信息来去噪声.与常用的双线性滤波.中值滤波等利用图 ...

  2. 如何用vue实现一个矩形标记区域 rectangle marker

    代码地址:vue-rectangle-marker 一.前言 一些cms系统经常会用到区域标记功能,所以写了个用vue实现的矩形标记区域,包含拖拽.放大缩小.重置功能. 二.实现结果 初始 标记 三. ...

  3. Java中的微信支付(1):API V3版本签名详解

    1. 前言 最近在折腾微信支付,证书还是比较烦人的,所以有必要分享一些经验,减少你在开发微信支付时的踩坑.目前微信支付的API已经发展到V3版本,采用了流行的Restful风格. 今天来分享微信支付的 ...

  4. [SuProxy]Ngnix+Lua 实现SSH2,LDAP,ORACLE,SQLSERVER等TCP/IP协议分析,劫持,代理,会话及负载

    目录 目录 目录 前言 介绍 安装 下载并拷贝 使用LuaRocks安装 运行测试 使用简介 处理器(processor)创建 通道(channel)创建 负载均衡 会话信息和会话管理 Event H ...

  5. SPI、I2C、I2S、UART、GPIO、SDIO、CAN、JTAG的区别及使用方法。

    SPI 全称及由来:SPI接口的全称是"Serial Peripheral Interface",意为串行外围接口,是Motorola首先在其MC68HCXX系列处理器上定义的. ...

  6. 【面经】面试官:如何以最高的效率从MySQL中随机查询一条记录?

    写在前面 MySQL数据库在互联网行业使用的比较多,有些小伙伴可能会认为MySQL数据库比较小,存储不了很多的数据.其实,这些小伙伴是真的不了解MySQL.MySQL的小不是说使用MySQL存储的数据 ...

  7. Maven魔法堂:安装Oracle JDBC Driver依赖的那些坑

    前言 由于Oracle并没有向公开Maven仓库提供任何Oracle JDBC Driver的Jar包,因此我们无法像MySQL.SQLite等那么轻松直接通过Maven加载依赖. 而手动下载Orac ...

  8. pytorch加载语音类自定义数据集

    pytorch对一下常用的公开数据集有很方便的API接口,但是当我们需要使用自己的数据集训练神经网络时,就需要自定义数据集,在pytorch中,提供了一些类,方便我们定义自己的数据集合 torch.u ...

  9. .net 实现 一二级分类

    public List<Model.Category> CategoryPid(int id = 0) { string sql = "select * from categor ...

  10. 18 socket

    18 socket 推荐: http://www.360doc.com/content/11/0609/15/5482098_122692444.shtml Socket=Ip address+ TC ...