Search code examples
javamavensonarqube

Skip sonar plugin execution if maven tests are skipped


I have set up Sonar as maven plugin in my pom, and would like the plugin to run only if tests are run. Use case is I want the sonar plugin to run on my CI server, but not when packaging the jar. So mvn test should execute the sonar plugin, but mvn -DskipTests clean package should not.

Today the sonar plugin are running also when I skip the tests.

My setup today:

<sonar.host.url>https://sonar.myserver.no</sonar.host.url>
<sonar.login>my token</sonar.login>
<sonar.projectName>My app</sonar.projectName>
.....
<plugin>
    <groupId>org.sonarsource.scanner.maven</groupId>
    <artifactId>sonar-maven-plugin</artifactId>
    <version>${sonar.maven.plugin.version}</version>
    <executions>
        <execution>
            <id>sonar</id>
            <phase>test</phase>
            <goals>
                <goal>sonar</goal>
            </goals>
        </execution>
    </executions>
</plugin>


Solution

  • With every plugin, we can add section

    <configuration>
        ...
        <skip>...</skip>
        ...
    </configuration>
    

    in an <execution>-block to control when the execution should be skipped. In the given case, we can bind the skip logic to the property skipTests:

    <plugin>
        <groupId>org.sonarsource.scanner.maven</groupId>
        <artifactId>sonar-maven-plugin</artifactId>
        <version>${sonar.maven.plugin.version}</version>
        <executions>
            <execution>
                <id>sonar</id>
                <phase>test</phase>
                <goals>
                    <goal>sonar</goal>
                </goals>
                <configuration>
                    <skip>${skipTests}</skip>
                </configuration>
            </execution>
        </executions>
    </plugin>