问题
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?).
回答1:
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
回答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:
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
.
来源:https://stackoverflow.com/questions/49406872/verify-that-assertions-have-been-called-in-assertj