我使用PowerMockito模拟包含私有方法的类实例。而我想验证私有方法返回值是否正确,那么如何使用PowerMock调用私有方法并获取返回值? 这是演示:
class Demo {
public publicMethod1ReturnClass publicMethod1() {
// do something...
}
private privateMethod1ReturnClass privateMethod1() {
// do something
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(Demo.class)
class DemoTest {
@Test
public void test() throws Exception {
Demo demo = PowerMockito.spy(new Demo());
privateMethod1ReturnClass result = demo.privateMethod1();
}
}
答案 0 :(得分:1)
您可以使用Whitebox
这样做,
privateMethod1ReturnClass s = Whitebox.invokeMethod(demo, "privateMethod1");
assertEquals(s, "yourExpectedResult");