我是 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 ...
}
}
我有一个类,其中包含一个我想模拟的私有(private)方法,名为 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 ...
}
}
根据上面的代码,当我运行上面的测试时,每当在 methodUsingThePrivateMethod()
中调用 methodIWantToMock
时,PowerMockito 应该简单地返回一个空值。然而,实际发生的是,当运行此命令时:PowerMockito.doReturn(...).when(...)
,PowerMockito 实际上正在调用 methodIWantToMock
就在那儿!! 为什么要那样做??在这个阶段,我只想指定当 coiSpy.methodUsingThePrivateMethod();
行被调用时它应该如何模拟私有(private)方法最终跑。
最佳答案
所以我想出了一个适合我的解决方案。我没有使用 spy
,而是使用了 mock
,然后告诉 PowerMockito 在我的模拟对象中调用 methodUsingThePrivateMethod()
时调用真正的方法.它本质上是在做与以前相同的事情,只是使用了 mock
而不是 spy
。这样,PowerMockito 不会最终调用我试图使用 PowerMockito.doReturn(...).when(...)
控制其行为的私有(private)方法。这是我修改后的测试代码。我更改/添加的行已标记:
@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 ...
}
}
关于java - 当我使用 doReturn(..).when(....) 时,PowerMockito 正在调用该方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38155092/