Spring Framework tests must use AssertJ for assertions rather than JUnit's `Assertions`, Spring's `Assert` class, or plain `assert` statements. Follow these AssertJ best practices:
Spring Framework tests must use AssertJ for assertions rather than JUnit’s Assertions
, Spring’s Assert
class, or plain assert
statements. Follow these AssertJ best practices:
// PREFERRED
assertThat(collection).hasSize(2);
// AVOID
assertThat(collection.size()).isEqualTo(2);
// PREFERRED
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() -> {
jdbcTemplate.queryForList("SELECT name FROM user", String.class);
});
// AVOID
try {
jdbcTemplate.queryForList("SELECT name FROM user", String.class);
fail("BadSqlGrammarException should have been thrown");
}
catch (BadSqlGrammarException expected) {
}
// PREFERRED
assertThatCode(() -> {
Assert.noNullElements(asList("foo", "bar"), "enigma");
}).doesNotThrowAnyException();
// AVOID
Assert.noNullElements(asList("foo", "bar"), "enigma"); // Missing verification
Using AssertJ consistently provides more readable tests, better failure messages, and ensures test consistency throughout the codebase.
Enter the URL of a public GitHub repository