通过PowerMock轻松模拟私有方法。但是我的用例是模拟从Public静态方法调用的私有方法。
示例代码:
public class PrivateMethodMockExample {
public int sumTwoNumbers() {
int a = returnFirstNumber();
int b = 5;
return a + b;
}
public static int sumTwoNumbersStaticMethod() {
PrivateMethodMockExample privateMethodMockExample = new PrivateMethodMockExample();
int a = privateMethodMockExample.returnFirstNumber();
int b = 5;
return a + b;
}
private int returnFirstNumber() {
return 10;
}
}
测试类:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
@RunWith(PowerMockRunner.class)
@PrepareForTest(PrivateMethodMockExample.class)
public class PrivateMethodMockExampleTest {
@Test
public void testSumMethod() throws Exception {
final String methodToTest = "returnFirstNumber";
PrivateMethodMockExample instance = PowerMock.createPartialMock(PrivateMethodMockExample.class, methodToTest);
PowerMock.expectPrivate(instance, methodToTest).andReturn(5);
PowerMock.replay(instance);
int result = instance.sumTwoNumbers();
PowerMock.verify(instance);
assertEquals(result, 10);
}
@Test
public void testStaticSumMethod() throws Exception {
final String methodToTest = "returnFirstNumber";
PrivateMethodMockExample instance = PowerMock.createPartialMock(PrivateMethodMockExample.class, methodToTest);
PowerMock.expectPrivate(instance, methodToTest).andReturn(5);
PowerMock.replay(instance);
int result = instance.sumTwoNumbersStaticMethod();
PowerMock.verify(instance);
assertEquals(result, 10);
}
}
第一个测试用例通过,但是第二个测试用例失败。 我感觉在某处概念上我错了。
当然,关于代码设计问题的辩论可能会很长。但是我需要以某种方式理解如何在不重构源类的情况下通过第二个测试用例。