# Use Dedicated Assertions
# Description
Testing for equality or null values using assertTrue
or assertFalse
makes the test code and the assertion failure messages harder to read and understand.
The dedicated assertions should be used instead.
This rule replaces the following boolean assertions:
assertTrue
assertFalse
with the corresponding dedicated assertions:
assertEquals
assertNotEquals
assertNull
assertNotNull
assertSame
assertNotSame
See the section below for more code examples.
Requirements
This rule requires one of the following libraries to be present:
- junit:junit:4.0
- org.junit.jupiter:junit-jupiter-api:5.0.0
# Benefits
Improves the readability of both, the test code and the assertion failure messages.
# Tags
# Code Changes
# Testing Equality
Pre
@Test
void equalityTesting() {
User expected = new User(0, "John", "Snow");
User other = new User(37, "John", "Snow");
User actual = userRepo.findById(0);
assertTrue(expected.equals(actual));
assertFalse(other.equals(actual));
}
Post
@Test
void equalityTesting() {
User expected = new User(0, "John", "Snow");
User other = new User(37, "John", "Snow");
User actual = userRepo.findById(0);
assertEquals(expected, actual);
assertNotEquals(other, actual);
}
# Testing Null Values
Pre
@Test
void nullnessTesting() {
User user = userRepo.findById(0);
User nullUser = userRepo.findById(-1);
assertTrue(user != null);
assertTrue(nullUser == null);
}
Post
@Test
void nullnessTesting() {
User user = userRepo.findById(0);
User nullUser = userRepo.findById(-1);
assertNotNull(user);
assertNull(nullUser);
}
# Constants as Expected Values
Pre
@Test
void usingConstantsAsExpectedValues() {
User user = userRepo.findById(0);
assertTrue(user.getFirstName().equals("John"));
}
Post
@Test
void usingConstantsAsExpectedValues() {
User user = userRepo.findById(0);
assertEquals("John", user.getFirstName());
}
# Comparing Primitives
Pre
@Test
void comparingPrimitives() {
User user = userRepo.findById("0");
assertTrue(0 == user.getId());
}
Post
@Test
void comparingPrimitives() {
User user = userRepo.findById("0");
assertEquals(0, user.getId());
}
# Comparing Same Objects
Pre
@Test
void compareSame() {
User user = userRepo.findById("0");
User actual = userRepo.save(user);
assertTrue(user == actual);
}
Post
@Test
void compareSame() {
User user = userRepo.findById("0");
User actual = userRepo.save(user);
assertSame(user, actual);
}
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.