Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMockito disables Sonar branch coverage

I'm using PowerMockito and @PrepareForTest annotation for my test class. When I do this, Sonar says none of the branches have been covered. However, my other test classes that don't use PowerMockito works well. For example:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ MyClass.class })
public class MyClassTest {
    //create some mocks and run some tests here
}

Is there anyone encountered with the same problem?

Thanks in advance.

like image 980
newbieee Avatar asked Jan 13 '15 15:01

newbieee


2 Answers

There is a known issue with PowerMockito and sonar code coverage calculation, and I did a big research on this - as of today, there is no fix to it. How I personally deal with it - try to avoid the usage of PowerMockito - so use static and final sparsely, which is generally a good advice to have more object oriented code anyway. However, there will still be a few cases were you will need to use static and or final. For these, compare my answer here: cobertura-showing-proper-coverage-but-in-sonar-many-files-showing-0-coverage

like image 123
Marcus Biel Avatar answered Oct 05 '22 18:10

Marcus Biel


  1. Add cobertura plugin to your sonar server
  2. Use the maven cobertura plugin in build (I assume that the build uses maven)
  3. Feed in cobertura and sonar related properties needed for reporting to your sonar server. example as shown.

    <sonar.java.coveragePlugin>cobertura</sonar.java.coveragePlugin>
    <sonar.host.url>http://localhost:9500</sonar.host.url>    
    <sonar.sources>${project.build.sourceDirectory}</sonar.sources>
    <sonar.junit.reportsPath>${project.build.directory}/surefire-reports</sonar.junit.reportsPath>
    <sonar.cobertura.reportPath>${project.build.directory}/site/cobertura/coverage.xml</sonar.cobertura.reportPath>
    
  4. Run maven goal for sonar i.e., mvn install sonar:sonar

like image 28
maggu Avatar answered Oct 05 '22 19:10

maggu