Powermock and sonar jacoco的覆盖率不兼容问题解决 3

上一篇介绍了如何让surefire,failsafe和jacoco maven plugin如何结合配置,这一篇具体说说如何使用powermock的agent来解决覆盖率不兼容问题。
首先在pom中加入powermock agent maven依赖

<dependency>
  <groupId>org.powermockgroupId>
  <artifactId>powermock-module-junit4-rule-agentartifactId>
  <version>${powermock.version}version>
  <scope>testscope>
dependency>

Note: It’s recommended that you put powermock-module-junit4-rule-agent before junit in the classpath. (记得把这个dependency放到junit之前)。

接下来修改之前的测试代码:
修改之前的实现

@RunWith(PowrMockRunner.class)
@PrepareForTest(X.class);
public class MyTest {
     private X x;
     @Before
     public void setUp {
        x=PowerMockito.mock(X.class);
     }
     // Tests goes here
     ...
}

修改之后的实现
去掉runwith,加入@Rule annotation,很简单!

@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
     ...
}

最后据说在mock final的时候要在surefire的启动参数中加入agent启动参数,这种mock我们没有使用,不过还是加上了。

<plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-surefire-pluginartifactId>
                <version>2.15version>
                <configuration>
                    <argLine>
                        -javaagent:${settings.localRepository}/org/powermock/powermock-module-javaagent/${powermock.version}/powermock-module-javaagent-${powermock.version}.jar -XX:-UseSplitVerifier ${surefireArgLine}
                    argLine>                    <useSystemClassloader>trueuseSystemClassloader>
                configuration>
            plugin>

在我们项目中最后3种使用方式覆盖率的差别,可以看出Cobertura还是有最高的覆盖率,使用了powermock agent之后覆盖率也算不错。

Powermock&Jacoco Powermock Agent&Jacoco Powermock&Cobertura
10% 50% 60%

参考资料:https://github.com/jayway/powermock/wiki/PowerMockAgent

你可能感兴趣的:(maven,sonar,Java)