![](/img/trans.png)
[英]How to use PowerMockito to mock new class instance inside a static method
[英]PowerMockito doesn't mock the new instance called in the tested class
我有以下类,在构造函数中,我调用另一个构造函数来构建类的字段:
public class ClassIWantToTest {
private ClassIWantToMock anotherClass;
public ClassIWantToTest() {
//some stuff
anotherClass = new ClassIWantToMock(); //<-- call constructor to build the field
//some other stuff
}
}
当我测试类ClassIWantToTest
,我想模拟ClassIWantToMock
的实例。
因此,我按如下方式设置了我的测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassIWantToMock.class)
public class ClassIWantToTest_Test {
@Test
public void myFirstTest() {
ClassIWantToMock myMock = PowerMockito.mock(ClassIWantToMock.class);
PowerMockito.whenNew(ClassIWantToMock.class).withAnyArguments().thenReturn(myMock);
ClassIWantToTest test = new ClassIWantToTest(); //<-- not mocked
}
}
但是,在测试的最后一行代码中(我创建了一个我要测试的类的new
),仍然会调用ClassIWantToMock
的构造函数。
我已经在Stack Overflow(以及文档)中搜索了其他示例,但它似乎应该像这样完成。 我忘了/做错了什么?
这确实是一个简单的错误。 如果类ClassIWantToMock
被初始化里面ClassIWantToTest
,那么也ClassIWantToTest
应为测试准备。
我替换了这个:
@PrepareForTest(ClassIWantToMock.class)
有了这个:
@PrepareForTest({ClassIWantToTest.class,ClassIWantToMock.class})
......它运作良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.