Powermockito whenNew returns 如果不匹配则为 null

Powermockito whenNew returns null if not matched

我不知道它是否应该这样做,但我想不会。看看下面我的代码。

File mocked = PowerMockito.mock(File.class);    
PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(eq(THE_TARGET_PATH)).thenReturn(mocked);
File normalFile = new File(WORKING_PATH);
File mockedFile = new File(THE_TARGET_PATH);

我确实希望 normalFile 能够正常创建,但实际上是 nullmockedFile 被正确地嘲笑了。

我也在用@RunWith(PowerMockRunner.class)@PrepareForTest({ClassWhereInstanceIsCreated.class, File.class})

我正在使用:

<dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-core</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>

我的发现表明,没有好的方法可以使用 PowerMockito / PowerMockito 2 进行部分构造函数模拟。按照逻辑,您应该能够做类似的事情

PowerMockito.whenNew(File.class).withParameterTypes(String.class)
                                .withArguments(eq(WORKING_PATH)).thenCallRealMethod();

但这会在 PowerMockito 中触发类似于此的内部异常

org.mockito.exceptions.base.MockitoException: Cannot call abstract real method on java object! Calling real methods is only possible when mocking non abstract method. //correct example: when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();

因此,我能看到的唯一方法就是重新编写测试。在模拟构造函数之前,您应该首先构造所有需要的 File 对象,并在每种特定情况下为 return 提供 PowerMockito 规则。

File mocked = Mockito.mock(File.class);
// create file as you want
File realFile = new File(WORKING_PATH);
// tell PowerMockito to return it
PowerMockito.whenNew(File.class).withParameterTypes(String.class)
            .withArguments(Mockito.eq(WORKING_PATH)).thenReturn(realFile);
// tell PowerMockito to return mock if other argument passed
PowerMockito.whenNew(File.class).withParameterTypes(String.class)
            .withArguments(Mockito.eq(THE_TARGET_PATH)).thenReturn(mocked);

File normalFile = new File(WORKING_PATH);
File mockedFile = new File(THE_TARGET_PATH);

这是不受欢迎的解决方案,但我无法提供更好的解决方案。

希望对您有所帮助!