Write better unit tests in Java thanks to a new set of rules dedicated to JUnit

Hello Java developers,

Whether you are a novice or an expert in writing unit tests, you will enjoy the 10 additional rules we added to help you write better unit tests. These rules come on top of the 15 existing ones already there focusing on tests. Among these 25 rules, 21 are JUnit-related.
These rules are mainly based on JUnit documentation which provides a lot of explanations to correctly use the framework.

Here is the full list of the new rules:

Bug Rules:

  • S5779: Assertion methods should not be used within the try block of a try-catch catching an Error (Critical)
  • S5783: Only one method invocation is expected when testing checked exceptions (Critical)
  • S5790: JUnit5 nested test classes should be annotated with @Nested (Critical)
  • S5810: JUnit5 test classes and methods should not have private visibility (Major)

Code Smell Rules:

  • S5776: Exception testing via JUnit ExpectedException should not be mixed with other assertions (Major)
  • S5778: Only one method invocation is expected when testing runtime exceptions (Major)
  • S5785: JUnit assertTrue/assertFalse should be simplified to its dedicated assertion (Major)
  • S5777: Exception testing via JUnit @Test annotation should be avoided (Minor)
  • S5786: JUnit5 test classes and methods should have default package visibility (Info)
  • S5793: Migrate your tests from JUnit4 to the new JUnit5 annotations (Info)

For more information, you can check the changelog.

These features are already available on SonarCloud, and will be included soon in SonarQube 8.4 and SonarLint.