DEV Community

Cosmas Gikunju
Cosmas Gikunju

Posted on

How to add SonarQube Code Coverage to Spring Boot

1. Overview

SonarQube is a self-managed static code analysis tool for continuous codebase inspection provided by SonarSource.

It's a popular choice used by organizations to :

  • Finding and fix bugs and security vulnerabilities in code.
  • Analyze code with Static Application Security Testing (SAST).
  • Detect a broad range of security issues such as SQL injection vulnerabilities, cross-site scripting (XSS) code injection attacks, buffer overflows, authentication issues, cloud secrets detection and much more.
  • Perform branch analysis to spot and eliminate bugs.

You can

In this article we will look at how to add Coverage to your Spring Boot and Java application.

2. Integrating Sonarqube to your spring boot project

  • Add JaCoCo plugin to your dependencies on the pom.xml file as follows:
Enter fullscreen mode Exit fullscreen mode

Work with the version of choice , you can search at Maven Central

  • Then add the following under build plugins:

Enter fullscreen mode Exit fullscreen mode

There is a very good post at that explains importing JaCoCo coverage report in XML format.

And voila, that's all you need to do.

3. Testing

  • Download and run sonarqube via docker: docker run -d -p 9000:9000 sonarqube

Then access the dashboard at : http://localhost:9000

  • Back at your project directory run mvn clean install to build your code then mvn sonar:sonar to sync to sonarqube.

  • Back at your sonar dashboard you will see your coverage info as follows:

Sonar Dashboard Screenshot

4. Caveat

  • To exclude packages or files from the coverage add them as following in the properties section of your pom.xml :
Enter fullscreen mode Exit fullscreen mode

Run mvn clean install then mvn sonar:sonar and your coverage will update. If a devops pipeline is set, just push your changes and you will see them at your sonarqube dashboard.

  • You can also add the Sonarlint plugin/extension to your IDE or Code Editor to allow you catch most of the issues before you commit or build.

Top comments (0)