前言
本篇文章将说明如何使用PowerMock
对静态私有方法进行Mock
。关于使用PowerMock
需要引入哪些依赖,请参考PowerMock使用-依赖准备。
正文
被测试类如下所示。
public class MockStaticPrivateMethod {
public static boolean isTrue() {
return returnTrue();
}
private static boolean returnTrue() {
return true;
}
}
被测试类中有一个静态公共方法isTrue()
,在isTrue()
方法中会调用MockStaticPrivateMethod
的静态私有方法returnTrue()
。测试程序如下所示。
@RunWith(PowerMockRunner.class)
@PrepareForTest(MockStaticPrivateMethod.class)
public class PowerMockTest {
@Test
public void mockStaticPrivate() throws Exception {
PowerMockito.mockStatic(MockStaticPrivateMethod.class);
PowerMockito.when(MockStaticPrivateMethod.class, "returnTrue")
.thenReturn(false);
PowerMockito.when(MockStaticPrivateMethod.isTrue()).thenCallRealMethod();
assertThat(MockStaticPrivateMethod.isTrue(), is(false));
}
}
同样测试代码对业务代码造成了入侵,可以使用Whitebox
来方便的调用静态私有方法,如下所示。
public class MockStaticPrivateMethod {
private static boolean returnTrue() {
return true;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(MockStaticPrivateMethod.class)
public class PowerMockTest {
@Test
public void mockStaticPrivate() throws Exception {
PowerMockito.mockStatic(MockStaticPrivateMethod.class);
PowerMockito.when(MockStaticPrivateMethod.class, "returnTrue")
.thenReturn(false);
assertThat(Whitebox.invokeMethod(MockStaticPrivateMethod.class, "returnTrue"),
is(false));
}
}