# 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);
}
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.