4

I'm reading through test classes that use Assertj to verify results. Occasionally, I've spotted an assertThat without assertions.

assertThat(object.getField());

Is it possible to identify these classes somewhere in the development cycle? My first guess would be to use a custom Sonar rule. Although I don't see how I should define that this method should be followed by an assertion (a method returning void?).

TomVW
  • 1,510
  • 13
  • 26

2 Answers2

4

SonarJava is having the rule S2970 "Assertions should be complete" that can detect assertThat without assertions for AssertJ, Fest and Truth.

See: https://rules.sonarsource.com/java/RSPEC-2970

Nat
  • 3,587
  • 20
  • 22
2

As said in the AssertJ FAQ:

Static code analysis tools like SpotBugs/FindBugs/ErrorProne can now detect such problems thanks to the CheckReturnValue annotation introduced in 2.5+ / 3.5+ and improved in 2.7+ / 3.7+.

And indeed, SpotBugs finds this issue easily as I just tested with AssertJ 3.9.0, Java 8 and SpotBugs 3.1.1: SpotBugs: "Return value of <code>assertThat()</code> ignored"

Therefore, if you do not see this warning in your static analysis tool, perhaps you have disabled the check for using return values from methods annotated with @CheckReturnValue.

Petr Janeček
  • 37,768
  • 12
  • 121
  • 145