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. 变量分割技术、判别学习(discriminative learning method)

    基于模型的优化方法(model-based optimization method): 小波变换.卡尔曼滤波.中值滤波.均值滤波: 优点:对于处理不同的逆问题都非常灵活:缺点:为了更好的效果而采用各种 ...

  2. 运行Apache时出现the requested operation has failed

    在修改自己主机E:\wamp\apache\conf中的httpd.conf中的站点位置后,重新运行Apache时,出现对话框提示"the requested operation has f ...

  3. linux开机启动设置的几种方法

    Linux开机自启动的几种方式: 1.chkconfig 以supervisord服务脚本为例: 第1步:把上面的脚本放在/etc/init.d/文件 ln -s ./supervisord  /et ...

  4. Flink的DataSource三部曲之三:自定义

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  5. DM的SQL优化入门笔记

    1.查看执行计划EXPLAIN SELECT A.C1+1,B.D2 FROM T1 A, T2 B WHERE A.C1 = B.D1; 2.执行计划: 1 #NSET2: [0, 16, 9] 2 ...

  6. 找出"吸血鬼数"(Java)

    吸血鬼数是指位数为偶数的数字,可以由一 对数字相乘而得到,而这对数字各包含乘积的一半 位数的数字,其中从最初的数字中选取的数字可以任意排序.以两个0结尾的数字是不允许的,例如,下列数字都是 " ...

  7. 云计算之路-出海记:命令行下的 AWS

    俗话说"三百六十行,行行出状元",自从有了电脑之后,三百六十行又多了一行 -- 命令行.GUI 的诞生开创了繁荣的 PC "窗口"(windows)时代,互联网 ...

  8. tp3.2验证码

    切换验证码 document.getElementById('img_code_1').src="__URL__/verify/"+Math.random(1,9999); 生成验 ...

  9. Spider_基础总结5--动态网页抓取--元素审查--json--字典

    # 静态网页在浏览器中展示的内容都在HTML的源码中,但主流网页使用 Javascript时,很多内容不出现在HTML的源代码中,此时仍然使用 # requests+beautifulsoup是不能够 ...

  10. JavaScript探秘:可执行的上下文堆栈

    这一系列的文章,挺不错的,值得收藏细读 JavaScript探秘:可执行的上下文堆栈