The previous article describes how to let Surefire,failsafe and Jacoco maven plugin How to combine configuration, this article specifically explains how to use the Powermock agent to solve coverage incompatibility problems.
First add Powermock agent maven dependency in POM
<dependency>
<groupId>org.powermock</groupId>
<artifactId> Powermock-module-junit4-rule-agent</artifactid>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
Note:it ' s recommended that's put powermock-module-junit4-rule-agent before JUnit in the classpath. (Remember to put this dependency before JUnit).
Next, modify the previous test code:
Implementation prior to modification
@RunWith (Powrmockrunner.class)
@PrepareForTest (x.class);
public class MyTest {
private x x;
@Before public
void SetUp {
x=powermockito.mock (x.class);
}
Tests goes here
...
}
The implementation after the modification
Remove Runwith, add @rule annotation, very simple.
@PrepareForTest (x.class);
public class MyTest {
@Rule
powermockrule rule = new Powermockrule ();
private x x;
@Before public
void SetUp {
x=powermockito.mock (x.class);
}
Tests goes here
...
}
Finally, it is said that in the mock final the agent startup parameters are added to the Surefire startup parameters, which we did not use, but added.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId> maven-surefire-plugin</artifactid>
<version>2.15</version>
<configuration>
<argLine>
-javaagent:${settings.localrepository}/org/powermock/powermock-module-javaagent/${ Powermock.version}/powermock-module-javaagent-${powermock.version}.jar-xx:-usesplitverifier ${surefireArgLine}
</argLine> <useSystemClassloader>true</useSystemClassloader>
</configuration >
</plugin>
In our project the last 3 ways to use the coverage of the difference, you can see that Cobertura still has the highest coverage, the use of Powermock agent after the coverage is also good.
Powermock&jacoco Powermock Agent&jacoco Powermock&cobertura
10% 50% 40g
References: https://github.com/jayway/powermock/wiki/PowerMockAgent