如何模拟使用 PowerMockito 从构造函数调用的私有方法
How to Mock private method which is called from the constructor using PowerMockito
问题示例:
class ToBeTested {
private MyResource myResource;
public toBeTested() {
this.myResource = getResource();
}
private MyResource getResource() {
//Creating My Resource using information form a DB
return new MyResource(...);
}
}
我想模拟 getResource()
,这样我就可以提供 MyResource
的模拟实例。我找到的所有关于如何模拟私有方法的示例都是基于首先创建 ToBeTested
实例然后替换函数但是因为在我的例子中它是从构造函数调用的所以它已经很晚了。
是否可以在创建实例之前模拟所有实例的私有函数?
不直接,但是,您可以suppress然后用 power mockito 模拟
@RunWith(PowerMockRunner.class)
@PrepareForTest(ToBeTested .class)
public class TestToBeTested{
@before
public void setup(){
suppress(method(ToBeTested.class, "getResource"));
}
@Test
public void testMethod(){
doAnswer(new Answer<Void>() {
@Override
public MyResource answer(InvocationOnMock invocation) throws Throwable {
return new MyResource();
}
}).when(ToBeTested.class, "getResource");
}
ToBeTested mock = mock(ToBeTested.class);
mock.myMethod();
//assert
}
问题示例:
class ToBeTested {
private MyResource myResource;
public toBeTested() {
this.myResource = getResource();
}
private MyResource getResource() {
//Creating My Resource using information form a DB
return new MyResource(...);
}
}
我想模拟 getResource()
,这样我就可以提供 MyResource
的模拟实例。我找到的所有关于如何模拟私有方法的示例都是基于首先创建 ToBeTested
实例然后替换函数但是因为在我的例子中它是从构造函数调用的所以它已经很晚了。
是否可以在创建实例之前模拟所有实例的私有函数?
不直接,但是,您可以suppress然后用 power mockito 模拟
@RunWith(PowerMockRunner.class)
@PrepareForTest(ToBeTested .class)
public class TestToBeTested{
@before
public void setup(){
suppress(method(ToBeTested.class, "getResource"));
}
@Test
public void testMethod(){
doAnswer(new Answer<Void>() {
@Override
public MyResource answer(InvocationOnMock invocation) throws Throwable {
return new MyResource();
}
}).when(ToBeTested.class, "getResource");
}
ToBeTested mock = mock(ToBeTested.class);
mock.myMethod();
//assert
}