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