gpt4 book ai didi

java - PowerMockito 不会模拟测试类中调用的新实例

转载 作者:行者123 更新时间:2023-12-02 04:19:20 27 4
gpt4 key购买 nike

我有以下类,在构造函数中,我调用另一个构造函数来构建该类的字段:

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(和文档)上搜索了其他示例,但似乎应该这样做。我忘记了什么/做错了什么?

最佳答案

这确实是一个简单的错误。如果类 ClassIWantToMockClassIWantToTest 内部初始化,那么 ClassIWantToTest 也应该准备好进行测试。

我替换了这个:

@PrepareForTest(ClassIWantToMock.class)

这样:

@PrepareForTest({ClassIWantToTest.class,ClassIWantToMock.class})

...效果很好。

关于java - PowerMockito 不会模拟测试类中调用的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56646249/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com