Unit tests coverage using Jacoco for test classes

2020-03-06 04:33发布

问题:

I am trying to get the code coverage report on the sonarqube dashboard on jenkins. The code coverage report is coming up but showing only 4.6% coverage. On investigating I found out that the test classes written using PowerMocks are getting skipped.

On further investigation I found that "JaCoCo doesn't play well with dynamically modified/created classes (this is the way how powermock works). This is a known limitation we can't currently do anything about".

Is there any work around for this so that I can get proper code coverage for test classes written using PowerMocks too.

回答1:

Simple answer: no, there isn't.

Long answer - boils down to these options:

  • have look into this Wiki page by the PowerMock team - maybe maybe "offline instrumentation" works out for you.
  • hope that the corresponding bug gets fixed at some point (I wouldn't hold my breath on that)
  • get rid of your dependency to PowerMock(ito) - by refactoring and improving your production code
  • [ I think I evaluated various coverage tools long time ago; and there was one commercial one that claims to work even with PowerMock. But I don't recall any specifics. So I am basically saying: there might be a minuscule chance that another, proprietary coverage tool works with PowerMock ]


回答2:

I have managed to generate PowerMock coverage with Jacoco, using powermock-module-javaagent.

Just make sure you put powermock agent after jacoco agent:

<artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <useSystemClassLoader>true</useSystemClassLoader>
                <argLine>${jacocoArgLine} -javaagent:${settings.localRepository}/org/powermock/powermock-module-javaagent/${powermock.version}/powermock-module-javaagent-${powermock.version}.jar -noverify</argLine>
...

If you want to see an example, take a look at this project: https://github.com/jfcorugedo/sonar-scanner

Here you can see that sonar takes into account static methods and new statements mocked by PowerMock:

If you want to mock newstatements make sure you use PowerMockRule instead of PowerMockRunner.

Take a look at this test