PowerMockito.whenNew 不工作

PowerMockito.whenNew isn't working

更新。最后检查工作示例。


我有一个 class:

package test;

public class ClassXYZ {
    private final String message;

    public ClassXYZ() {
        this.message = "";
    }

    public ClassXYZ(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "ClassXYZ{" + message + "}";
    }
}

和一个测试:

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
public class MockClassXYZ {

    @Test
    public void test() throws Exception {
        PowerMockito.whenNew(ClassXYZ.class).withNoArguments().thenReturn(new ClassXYZ("XYZ"));

        System.out.println(new ClassXYZ());
    }
}

但它仍然创建一个真实的 class 并打印:

ClassXYZ{}

我做错了什么?

P.S. Maven 部门:

<dependencies>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.5.6</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.5.6</version>
        <scope>test</scope>
    </dependency>
</dependencies>

工作示例:

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassXYZ.class)
public class MockClassXYZ {
    @Test
    public void test() throws Exception {
        ClassXYZ mockXYZ = mock(ClassXYZ.class);
        when(mockXYZ.toString()).thenReturn("XYZ");

        PowerMockito.whenNew(ClassXYZ.class).withNoArguments().thenReturn(mockXYZ);

        ClassXYZ obj = new ClassXYZ();
        System.out.println(obj);
    }
}

您的测试 class 中缺少 @PrepareForTest(ClassXYZ.class),请参阅文档 here or here。从第一个link开始:

Mock construction of new objects

Quick summary

  1. Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
  2. Use the @PrepareForTest(ClassThatCreatesTheNewInstance.class) annotation at the class-level of the test case.

[...]


另请注意,如果您要求模拟框架 return 模拟 class.

的真实实例,则模拟构造函数毫无意义