1. Understand the Difference between Assertions and Exceptions
Assertions and exceptions are two completely different things, and using assertions in place of exceptions is not recommended.
Exceptions:
Handle unexpected runtime events.
Disrupt the normal flow of a program.
Meant to help the program recover from unexpected situations
Assertions:
Used to test and verify code assumptions.
Help improve code readability, documentation, testing, and debugging.
Represent invariants or properties that must be true or false at specific code points
2. Use assertTrue and assertFalse for Boolean Checks
Bad Code
// Redundant comparison
assertTrue(user.isLoggedIn() == true);
// Complex, hard-to-read conditional assertion
assertTrue(user.hasPermission("read") != false);
The improved version is:
// Clean, direct boolean assertions, Clearly checks login status
assertTrue(user.isLoggedIn());
// Multiple boolean checks with clear intent
assertAll(
() -> assertTrue(user.isAuthenticated(), "User should be authenticated"),
() -> assertTrue(user.hasPermission("read"), "User should have read permission")
);
3. Use assertNull and assertNotNull for Null Checks
This directly conveys the intention of the test, making the code more readable and easier to understand.
Bad Code
Using == null or != null can be less readable.
Assert.assertTrue(jsonPath.get("timestamp") != null, "Timestamp is miss");
The improved version is:
Although above code works, it can be made clearer and more expressive
by using assertNotNull
Assert.assertNotNull(jsonPath.get("timestamp"), "Timestamp is missing");
4. Use assertions to check preconditions and postconditions
Use assertions to check preconditions at the beginning of functions or methods to ensure that inputs are valid before executing the main logic.
In this example, the assertion checks a precondition (that x is positive) before proceeding with the rest of the method. If the assertion fails, it provides a clear error message.
public void testMethod(int x) {
assert x > 0 : "x must be positive";
System.out.println("x is positive");
}
5. Use Descriptive Assertion Messages
Always include a message in your assertions to explain what is being tested and why it might fail.
Avoid complex assertions that are hard to read and understand. Instead, break them down into smaller, simpler assertions.
Top comments (0)