javamavenvisual-studio-codecode-coverage

Java Code Coverage in Visual Studio Code


I am using VSC for my Java project with maven help. I would like to use a Code Coverage tool but I lost the directions in the many possibilities you have.
My goals are:

  • run the Code Coverage goal with Maven;
  • Display the test coverage in VSC with a plugin like Coverage Gutter

Which Code Code coverage tool to use?
Can someone show me the right Maven plugin and the way to configure VSC?

Thanks,
S.


Solution

  • Prerequisites

    • Java Extension Pack extension
    • Coverage Gutters extension by ryanluker: To display test coverage generated
    • Live Preview extension by Microsoft: To render HTML files in VSCode
    • A maven project with some tests

    Steps

    Add the jacoco-maven-plugin to your pom.xml file. This plugin will generate a report of your code coverage.

    <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.8.4</version>
        <executions>
            <execution>
                <goals>
                    <goal>prepare-agent</goal>
                </goals>
            </execution>
            <execution>
                <id>report</id>
                <phase>prepare-package</phase>
                <goals>
                    <goal>report</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    

    Generate the jacoco report by running the following command in your terminal:

    mvn jacoco:prepare-agent test install jacoco:report
    

    You should see a newly created file target/site/jacoco/index.html.

    NOTE: Each time you make a change to your tests, you need to rerun the above command to ensure that the code coverage report is accurate.

    View detailed report

    Open the HTML file (target/site/jacoco/index.html) and click on the magnify icon in the top right corner of VS Code. (Live Preview extension must be installed) enter image description here

    enter image description here

    Show inline coverage

    Click on Watch in the bottom left toolbar of your VS Code. (Code Gutters extension must be installed) enter image description here

    Check out the class for which you wrote tests: enter image description here

    Green bars indicate that that code has been reached by your tests. Orange bars indicate a missed conditional check. Red bars indicate code that was not reached by your tests.

    References