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. margin 重叠问题深入探究

    margin 重叠问题 Margin Collapse 块的上外边距(margin-top)和下外边距(margin-bottom)有时合并(重叠)为单个边距,其大小为单个边距的最大值(或如果它们相等 ...

  2. 使用 k8s 搭建 confluence 6.10.x 版本

    将公司中已有的 confluence 服务迁移到 k8s 集群中,需要保留当前已有的数据.整体需要分为如下几个步骤: 备份 mysql 数据 备份 confluence 安装目录 备份 conflue ...

  3. Educational Codeforces Round 97 (Rated for Div. 2)

    补了一场Edu round. A : Marketing Scheme 水题 #include <cstdio> #include <algorithm> typedef lo ...

  4. Go的第一个Hello程序 简简单单 - 快快乐乐

    Go的第一个Hello程序 简简单单 - 快快乐乐 JERRY_Z. ~ 2020 / 10 / 29 转载请注明出处!️ 目录 Go的第一个Hello程序 简简单单 - 快快乐乐 一.Go程序开发基 ...

  5. 【转载】HPL与HPCG测试(一)

    来源:HPL与HPCG测试 (一) 一.HPL与HPCG 简介 1.HPL HPL 即 High Performance Linpack,它是针对现代并行计算集群的测试工具.用户不修改测试程序,通过调 ...

  6. PHP百度地图开发之距离计算的实例分享

    /** * 计算两个坐标之间的距离(米) * @param float $fP1Lat 起点(纬度) * @param float $fP1Lon 起点(经度) * @param float $fP2 ...

  7. Android Studio的第一次经历

    第一个简单APP的制作是从xml开始的,通过在java新建一个empty  activity,并在layout里找到对应的xml文件进行编写.每编写一个xml就要事先新建 一个对应的empty  ac ...

  8. 第4章 Function语意学

    第4章 Function语意学 目录 第4章 Function语意学 4.1 Member的各种调用方式 Nonstatic Member Function(非静态成员函数) virtual Memb ...

  9. Python如何快速复制序列?

    1 基本用法 把序列乘以一个整数,就会产生一个新序列.这个新序列是原始序列复制了整数份,然后再拼接起来的结果. l=[1,2,3] l2=l * 3 logging.info('l2 -> %s ...

  10. stm32与地磁传感器HMC5883L

    1.简介 霍尼韦尔 HMC5883L 是一种表面贴装的高集成模块,并带有数字接口的弱磁传感器芯片,应用于低成本罗盘和磁场检测领域.HMC5883L 包括最先进的高分辨率 HMC118X 系列磁阻传感器 ...