我是 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 ...
}
}
根据上面的代码,PowerMockito 应该简单地返回一个 nullmethodIWantToMock
被称为里面methodUsingThePrivateMethod()
当我运行上面的测试时。然而,实际发生的情况是,当运行此命令时:PowerMockito.doReturn(...).when(...)
, PowerMockito 实际上正在调用methodIWantToMock
就在那时,那里!为什么要这样做?在这个阶段,我只想指定它应该如何模拟私有方法。最终当coiSpy.methodUsingThePrivateMethod();
线路已运行。
所以我想出了一个适合我的解决方案。而不是使用spy
,我用了一个mock
然后告诉PowerMockito调用真正的方法methodUsingThePrivateMethod()
在我的模拟对象内部被调用。它本质上做与以前相同的事情,但只是使用mock
代替spy
。这样,PowerMockito 最终不会调用我试图控制其行为的私有方法PowerMockito.doReturn(...).when(...)
。这是我修改后的测试代码。我更改/添加的行已标记:
@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 ...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)