powermock使用过程中有一些知识点还是容易忘记或者不知道怎么用,本文就是把这些常用的知识点记录下来,方便后来查找使用
1.对静态方法进行verify时,每次verify前都需要调用verifyStatic方法,有多少个方法需要验证就调用多少次
PowerMockito.verifyStatic(MyStaticMethod.class, Mockito.atLeast(1));
MyStaticMethod.myStaticFunc(Mockito.any());
PowerMockito.verifyStatic(MyStaticMethod.class,Mockito.never());
MyStaticMethod.myStaticFunc1(Mockito.any());
2.使用powermock修改某变量的值(包括类变量和实例变量)
//反射修改某个变量的值。如果是要修改静态变量的值,那第一个参数传相应的Class即可。
public static void setInternalState(Object object, String fieldName, Object value)
//反射获取某个变量的值。如果要获取静态变量的值,那第二个参数传相应的Class即可。
public static Object getFieldValue(final Field field, final Object object)
//获取Field对象
Field field = Whitebox.getField(Class, "fieldName");
3.使用powermock mock私有静态方法或者类中的其中一个静态方法,
public class MyStaticMethod {
private static boolean privateStaticMethod(int num) {
if (num > 100) {
return true;
}
return false;
}
public static String publicStaticMethodInCallPrivateStatic(int num) {
return "privateStatic:" + privateStaticMethod(num);
}
}
@Test
public void testPrivateStatic() throws Exception {
MyStaticMethod inst = PowerMockito.spy(new MyStaticMethod());
PowerMockito.spy(MyStaticMethod.class);
PowerMockito.doReturn("myStaticFunc").when(MyStaticMethod.class, "myStaticFunc", Mockito.any());
PowerMockito.doReturn(true).when(MyStaticMethod.class, "privateStaticMethod", Mockito.anyInt());
Long num = 1000L;
String ret = inst.myDisplay(num);
Assert.assertTrue(ret.equals("myStaticFunc_yyyyy"));
// 验证静态方法myStaticFunc被调用过
PowerMockito.verifyStatic(MyStaticMethod.class, Mockito.atLeast(1));
MyStaticMethod.myStaticFunc(Mockito.any());
String publicRet = MyStaticMethod.publicStaticMethodInCallPrivateStatic(Mockito.anyInt());
Assert.assertEquals("privateStatic:true", publicRet);
//直接调用私有静态方法
boolean privateRet = Whitebox.invokeMethod(MyStaticMethod.class, "privateStaticMethod", Mockito.anyInt());
Assert.assertTrue(privateRet);
// 验证私有静态方法被调用过两次,一次是被public方法调用,一个是通过反射直接调用
PowerMockito.verifyPrivate(MyStaticMethod.class, Mockito.times(2)).invoke("privateStaticMethod", Mockito.anyInt());
}
关键代码行:PowerMockito.spy(MyStaticMethod.class);这样就可以mock私有静态方法或者类中的某几个方法.
4.怎么verify public静态方法的调用次数
// 验证公共静态方法,第一步verifyStatic,第二步跟着实际调用的静态方法
PowerMockito.verifyStatic(MyStaticMethod.class, Mockito.atLeast(1));
MyStaticMethod.myStaticFunc(Mockito.any());
5.怎么verify private静态方法的调用次数,和verify类实例的私有方法一样都是verifyPrivate方法
PowerMockito.verifyPrivate(MyStaticMethod.class, Mockito.times(2)).invoke("privateStaticMethod", Mockito.anyInt());
6.使用doAnswer根据不同的参数返回不同的返回值
PowerMockito.doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock var1) throws Throwable {
var1.getMock();
return "answer:" + var1.getArguments()[0];
}
}).when(inst, "myPrivateFunc", Mockito.any());
7.10
@Mock:可以是interface、class, 不会进去到具体的方法中,@InjectMocks:只能只对class,对于被mock的方法会返回mock的值,对于没有被mock的方法会进去到具体代码中去