TomVW
TomVW

Reputation: 1580

Verify that assertions have been called in Assertj

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?).

Upvotes: 5

Views: 1824

Answers (2)

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

Upvotes: 5

Petr Janeček
Petr Janeček

Reputation: 38444

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.

Upvotes: 3

Related Questions