1. mock new
@PrepareForTest
You need to put the class where the constructor is called into the @PrepareForTest annotation instead of
the class which is being constructed.
More info ref: https://github.com/powermock/powermock/wiki/MockConstructor
2. Issue: code coverage rate by jcoco dropped down 0, after put the tested class into @PrepareForTest().
I put the tested class into @PrepareForTest is for using PowerMockito.whenNew to return a mock instance.
The related test-case executed, but the coverage down to 0.
Solution: I added a factory method for the newed class, so that I can get a mock instance by mocking static method.
Code making the coverage rate to 0
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassA.class)
public ClassATest {
@InjectMocks
private ClassA classA;
@Test
public void test1(){
ClassB mockB = mock(ClassB.class);
PowerMockito.whenNew(ClassB.class).withAnyArguments().thenReturn(mockB);
classA.doSomething();
}
}
public class ClassA {
public void doSomething(){
ClassB b = new ClassB();
b.f();
}
}
public class ClassB {
public void f(){
System.out.println("f() invoked");
}
}
Code getting the right coverage rate
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassB.class)
public ClassATest {
@InjectMocks
private ClassA classA;
@Test
public void test1(){
ClassB mockB = mock(ClassB.class);
PowerMockito.mockStatic(ClassB.class);
PowerMockito.when(ClassB.class, "instance").thenReturn(mockB);
classA.doSomething();
}
}
public class ClassA {
public void doSomething(){
ClassB b = ClassB.instance();
b.f();
}
}
public class ClassB {
public static ClassB instance(){
return new ClassB();
}
public void f(){
System.out.println("f() invoked");
}
}
3. static mock
@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticMethodClass)
public class ClassInvokingStaticMethodTest {
@Test
public void test1(){
PowerMockito.mockStatic(StaticMethodClass);
PowerMockito.when(StaticMethodClass, staticMethodName, args ...).thenReturn(mockObj);
ClassInvokingStaticMethod.methodInvokingStaticMethod();
}
}
4. powermock dependency
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>