Custom SonarQube rules for Unit Tests

It’s a tutorial about creating new rules for SonarQube analysis to be applied to Unit Tests. It is not trivial and involves a few tricky database steps, so I want to share my tutorial about it.It’s a tutorial about creating new rules for SonarQube analysis to be applied to Unit Tests. It is not trivial and involves a few tricky database steps, so I want to share my tutorial about it.

I need a new rule

In our project we use (formely Sonar) to manage our code quality. It is a great tool and I recommend everyone to set it up and read its reports.

Recently, we’ve agreed that it’s better to use assertj assertions in our unit tests than JUnit’s. So I’ve decided to write a simple rule that checks if some of JUnit asserts assertTrue, assertFalse, assertNull and others are used. Then, I’ve discovered it’s not so easy to do it with Sonar:

  • only 10 code quality rules are applied to unit tests – they are in special repository PMD Unit Tests (source)
  • these 10 rules are disabled by default, you have to enable them by hand
  • you cannot add new rules to this group

However, it turned out it is doable with a small tricks.

Custom PMD Unit Tests rule tutorial

Create your XPath expression by following this tutorial on how to create custom PMD rule. There is a visual editor to test your rules as you develop them – that’s great. My XPath expression to avoid all JUnit assertions looks like this:

//PrimaryPrefix/Name[@Image='assertEquals' or @Image='assertNull' or @Image='assertNotNull' or @Image='assertSame' or @Image='assertNotSame' or @Image='assertArrayEquals' or @Image='assertTrue' or @Image='assertFalse']

Go to your Sonar installation, log in as an Administrator, head to Quality Profiles and select a profile that you use. Search for “xpath” and change Activation to Any. You should see two results like this:

Expand XPath rule template (dont’ worry that it says it’s deprecated) and then click Copy rule. Fill a form with message and XPath and save it. Then take a look at the bottom – you need an identifier of this rule:

You have created a PMD rule, now you need to move it to PMD Unit Tests group. Connect to Sonar’s MySQL database. Search for your rule by key:

mysql> select id, plugin_rule_key, plugin_name, parent_id, status from rules where plugin_rule_key='XPathRule_1385721910';
+-----+----------------------+----------------+-----------+-------------+
| id  | plugin_rule_key      | plugin_name    | parent_id | status      |
+-----+----------------------+----------------+-----------+-------------+
| 903 | XPathRule_1385721910 | pmd            | NULL      | DEPRECATED  |
+-----+----------------------+----------------+-----------+-------------+
1 row in set (0.00 sec)

Update plugin_name and status (remember to use appropiate primary key for id column):

mysql> update rules set plugin_name='pmd-unit-tests', status='READY' where id=903;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

There is one step left. Sonar will change this rule’s status to REMOVED on restart due to his boot checks. You need to trick him and change parent_id to other’s PMD Unit Tests rule. List all these rules and choose one’s identifier.

mysql> select id, plugin_name, status from rules where plugin_name='pmd-unit-tests';
+-----+----------------+---------+
| id  | plugin_name    | status  |
+-----+----------------+---------+
| 775 | pmd-unit-tests | READY   |
| 776 | pmd-unit-tests | READY   |
| 777 | pmd-unit-tests | READY   |
| 778 | pmd-unit-tests | READY   |
| 779 | pmd-unit-tests | READY   |
| 780 | pmd-unit-tests | READY   |
| 781 | pmd-unit-tests | READY   |
| 782 | pmd-unit-tests | READY   |
| 783 | pmd-unit-tests | READY   |
| 784 | pmd-unit-tests | READY   |
| 903 | pmd-unit-tests | READY   |
+-----+----------------+---------+
11 rows in set (0.00 sec)\

Choose any id you like, let’s say 775 and apply it as parent_id to your newly created rule:

mysql> update rules set parent_id=775 where id=903;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Go to your Quality profile and make sure your rule is active! Check it twice, it’s easy to forget that step. It’s all set up, enjoy your analysis!

You May Also Like

Spock, Java and Maven

Few months ago I've came across Groovy - powerful language for JVM platform which combines the power of Java with abilities typical for scripting languages (dynamic typing, metaprogramming).

Together with Groovy I've discovered spock framework (https://code.google.com/p/spock/) - specification framework for Groovy (of course you can test Java classes too!). But spock is not only test/specification framework - it also contains powerful mocking tools.

Even though spock is dedicated for Groovy there is no problem with using it for Java classes tests. In this post I'm going to describe how to configure Maven project to build and run spock specifications together with traditional JUnit tests.


Firstly, we need to prepare pom.xml and add necessary dependencies and plugins.

Two obligatory libraries are:
<dependency>
<groupid>org.spockframework</groupId>
<artifactid>spock-core</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
<version>${groovy.version}</version>
<scope>test</scope>
</dependency>
Where groovy.version is property defined in pom.xml for more convenient use and easy version change, just like this:
<properties>
<gmaven-plugin.version>1.4</gmaven-plugin.version>
<groovy.version>2.1.5</groovy.version>
</properties>

I've added property for gmaven-plugin version for the same reason ;)

Besides these two dependencies, we can use few additional ones providing extra functionality:
  • cglib - for class mocking
  • objenesis - enables mocking classes without default constructor
To add them to the project put these lines in <dependencies> section of pom.xml:
<dependency>
<groupid>cglib</groupId>
<artifactid>cglib-nodep</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.objenesis</groupId>
<artifactid>objenesis</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>

And that's all for dependencies section. Now we will focus on plugins necessary to compile Groovy classes. We need to add gmaven-plugin with gmaven-runtime-2.0 dependency in plugins section:
<plugin>
<groupid>org.codehaus.gmaven</groupId>
<artifactid>gmaven-plugin</artifactId>
<version>${gmaven-plugin.version}</version>
<configuration>
<providerselection>2.0</providerSelection>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupid>org.codehaus.gmaven.runtime</groupId>
<artifactid>gmaven-runtime-2.0</artifactId>
<version>${gmaven-plugin.version}</version>
<exclusions>
<exclusion>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
<version>${groovy.version}</version>
</dependency>
</dependencies>
</plugin>

With these configuration we can use spock and write our first specifications. But there is one issue: default settings for maven-surefire plugin demand that test classes must end with "..Test" postfix, which is ok when we want to use such naming scheme for our spock tests. But if we want to name them like CommentSpec.groovy or whatever with "..Spec" ending (what in my opinion is much more readable) we need to make little change in surefire plugin configuration:
<plugin>
<groupid>org.apache.maven.plugins</groupId>
<artifactid>maven-surefire-plugin</artifactId>
<version>2.15</version>
<configuration>
<includes>
<include>**/*Test.java</include>
<include>**/*Spec.java</include>
</includes>
</configuration>
</plugin>

As you can see there is a little trick ;) We add include directive for standard Java JUnit test ending with "..Test" postfix, but there is also an entry for spock test ending with "..Spec". And there is a trick: we must write "**/*Spec.java", not "**/*Spec.groovy", otherwise Maven will not run spock tests (which is strange and I've spent some time to figure out why Maven can't run my specs).

Little update: instead of "*.java" postfix for both types of tests we can write "*.class" what is in my opinion more readable and clean:
<include>**/*Test.class</include>
<include>**/*Spec.class</include>
(thanks to Tomek Pęksa for pointing this out!)

With such configuration, we can write either traditional JUnit test and put them in src/test/java directory or groovy spock specifications and place them in src/test/groovy. And both will work together just fine :) In one of my next posts I'll write something about using spock and its mocking abilities in practice, so stay in tune.