PowerMockito 不会模拟在测试中调用的新实例 class

PowerMockito doesn't mock the new instance called in the tested class

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

public class ClassIWantToTest {
    private ClassIWantToMock anotherClass;
    public ClassIWantToTest() {
        //some stuff
        anotherClass = new ClassIWantToMock(); //<-- call constructor to build the field
        //some other stuff
    }
}

当我测试 class 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
    }
}

然而,在测试的最后一行代码中(我在class中创建了一个new我想测试),ClassIWantToMock的构造函数仍然被调用.

我在 Stack Overflow(和文档)上搜索了其他示例,但似乎应该这样做。我 forgetting/doing 哪里错了?

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

我替换了这个:

@PrepareForTest(ClassIWantToMock.class)

有了这个:

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

...而且效果很好。