4

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


我有一堂课:

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());
    }
}

但它仍然创建了一个真正的类并打印:

类XYZ{}

我究竟做错了什么?

PS 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);
    }
}
4

1 回答 1

9

@PrepareForTest(ClassXYZ.class)您的测试课程中缺少 a ,请参阅此处此处的文档。从第一个链接:

新对象的模拟构造

快速总结

  1. @RunWith(PowerMockRunner.class)在测试用例的类级别使用注释。
  2. @PrepareForTest(ClassThatCreatesTheNewInstance.class)在测试用例的类级别使用注释。

[...]


另请注意,如果您要求模拟框架返回模拟类的真实实例,则模拟构造函数没有意义。

于 2015-07-28T16:57:01.847 回答