更新。最后检查工作示例。
我有一堂课:
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);
}
}