Update. Check working example in the end.
I've got a 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 + "}";
}
}
and a test:
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());
}
}
but it still creates a real class and prints:
ClassXYZ{}
What am I doing wrong?
P.S. Maven deps:
<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>
Working example:
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);
}
}
答案 0 :(得分:6)
You are missing a @PrepareForTest(ClassXYZ.class)
on your test class, see the documentation here or here. From the first link:
Mock construction of new objects
Quick summary
- Use the
@RunWith(PowerMockRunner.class)
annotation at the class-level of the test case.- Use the
@PrepareForTest(ClassThatCreatesTheNewInstance.class)
annotation at the class-level of the test case.[...]
Also note that there's no point of mocking the constructor if you ask the mocking framework to return a real instance of the mocked class.