我是PowerMockito的新手,并且有一个我不明白的行为。以下代码解释了我的问题:
public class ClassOfInterest {
private Object methodIWantToMock(String x) {
String y = x.trim();
//Do some other stuff;
}
public void methodUsingThePrivateMethod() {
Object a = new Object();
Object b = methodIWantToMock("some string");
//Do some other stuff ...
}
}
我有一个类,其中包含一个我要模拟的名为methodIWantToMock(String x)
的私有方法。在我的测试代码中,我正在执行以下操作:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassOfInterest.class)
public class ClassOfInterestTest {
@Test
public void someTestMethod() {
ClassOfInterest coiSpy = PowerMockito.spy(new ClassOfInterest());
PowerMockito.doReturn(null).when(coiSpy, "methodIWantToMock", any(String.class));
coiSpy.methodUsingThePrivateMethod();
//Do some stuff ...
}
}
根据上面的代码,当我运行上面的测试时,只要在methodIWantToMock
内调用methodUsingThePrivateMethod()
,PowerMockito就应该返回一个null。然而实际发生的是,当运行此命令时:PowerMockito.doReturn(...).when(...)
, PowerMockito实际上正在调用methodIWantToMock
然后就在那里!! 为什么这样做?在这个阶段,我只想说明在运行coiSpy.methodUsingThePrivateMethod();
行时,如果 最终 被调用,它应该如何模拟私有方法。
答案 0 :(得分:2)
So I figured out a solution that works for me. Instead of using a spy
, I used a mock
and then told PowerMockito to call the real method when methodUsingThePrivateMethod()
is called inside my mocked object. It's essentially doing the same thing as before but just using a mock
instead of a spy
. This way, PowerMockito does NOT end up calling the private method whose behavior I'm trying to control using PowerMockito.doReturn(...).when(...)
. Here is my modified test code. The lines I changed/added are marked:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassOfInterest.class)
public class ClassOfInterestTest {
@Test
public void someTestMethod() {
//Line changed:
ClassOfInterest coiMock = PowerMockito.mock(new ClassOfInterest());
//Line changed:
PowerMockito.doReturn(null).when(coiMock, "methodIWantToMock", any(String.class));
//Line added:
PowerMockito.when(coiMock.methodUsingThePrivateMethod()).thenCallRealMethod();
coiSpy.methodUsingThePrivateMethod();
//Do some stuff ...
}
}