powermock, 强力模拟

1. powermock是基于mockito或者easymock,TestNG之上的mock;
2. 提供了对于静态函数,私有函数的mock
4. 通过mock价值是直接使用的类;因为只有mock返回的代理实例才会有“预期”行为。反之,如果一个模拟的类是在测试代码中间接被使用,则mock失效,如果你无法把mock的实例(对象代理)传递给测试场景中需要使用到的内容。比如测试代码是topTask,Platform,Platform中内部通过调用RuleService来进行获取规则数据,Platform并没有提供接口为RuleService赋值,那么你即使模拟了RuleService来获取某个规则数据,无效,因为Platform中使用的实例和mock实例是两个实例。
 
上代码:
基类
public class ClassA {
public boolean getResult() {
return false;
}
 
public int caculatePublic(int a, int b) {
return caculate(a, b);
}
 
private int caculate(int a, int b) {
return a + b;
}
 
public static int getValue() {
return 1;
}
}
 
测试类:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
 
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;
 
/**
* @author Lorry
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassA.class)
public class TestClassA {
@Test
public void test() {
try {
ClassA ca = mock(ClassA.class);
assertFalse(ca.getResult());
when(ca.getResult()).thenReturn(true);
assertTrue(ca.getResult());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
 
@Test
public void testStatic() {
assertEquals(1, ClassA.getValue());
mockStatic(ClassA.class);
when(ClassA.getValue()).thenReturn(10);
assertEquals(10, ClassA.getValue());
}
 
//@Test
public void testPrivate() {
try {
//ClassA ca = spy(new ClassA());
//assertEquals(3, ca.caculatePublic(1, 2));
//when(ca.caculatePublic(Mockito.anyInt(), Mockito.anyInt())).thenCallRealMethod();
//when(ca, "caculate", 1, 2).thenReturn(99);
//assertEquals(99, ca.caculatePublic(1, 2));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
原文地址:https://www.cnblogs.com/xiashiwendao/p/6941985.html