Java一分钟之-PowerMock:静态方法与私有方法测试
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.assertEquals;
import static org.powermock.api.mockito.PowerMockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticAndPrivateMethodTest.class)
public class StaticAndPrivateMethodTest {
@Test
public void testStaticMethod() {
// 使用PowerMockito.mockStatic方法来模拟静态方法
mockStatic(StaticAndPrivateMethodTest.class);
when(StaticAndPrivateMethodTest.staticMethod()).thenReturn("mocked static");
assertEquals("mocked static", StaticAndPrivateMethodTest.staticMethod());
}
@Test
public void testPrivateMethod() throws Exception {
// 使用PowerMockito.spy方法来创建一个对象的模拟
StaticAndPrivateMethodTest testSpy = spy(new StaticAndPrivateMethodTest());
// 使用Whitebox.setInternalState来设置私有字段的值
Whitebox.setInternalState(testSpy, "privateField", "mocked private");
when(testSpy, method(StaticAndPrivateMethodTest.class, "privateMethod")).thenCallRealMethod();
assertEquals("mocked private", testSpy.privateMethod());
}
public static String staticMethod() {
return "original static";
}
private String privateMethod() {
return (String) Whitebox.getInternalState(this, "privateField");
}
private String privateField = "original private";
}
这个代码示例展示了如何使用PowerMock进行静态方法和私有方法的测试。在第一个测试中,我们模拟了静态方法的行为,使其返回一个固定的mock值。在第二个测试中,我们通过PowerMock的Whitebox
类间接设置了私有字段的值,并且模拟了私有方法,使其在调用时返回这个mock值。
评论已关闭