How to Use assertEquals in JUnit for Testing
Use
assertEquals(expected, actual) in JUnit to check if two values are equal during a test. If they are not equal, the test fails and shows an error message. This method helps verify that your code works as expected.Syntax
The assertEquals method compares two values: the expected value and the actual value returned by your code. If they are equal, the test passes; if not, it fails.
Optional message can be added as the first argument to show a custom error message when the test fails.
java
assertEquals(expected, actual); assertEquals(message, expected, actual);
Example
This example shows a simple JUnit test using assertEquals to check if a method returns the correct sum of two numbers.
java
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CalculatorTest { public int add(int a, int b) { return a + b; } @Test public void testAdd() { CalculatorTest calculator = new CalculatorTest(); int result = calculator.add(2, 3); assertEquals(5, result, "Sum should be 5"); } }
Output
Test passed successfully with no errors.
Common Pitfalls
- Mixing up the order:
assertEqualsexpects expected value first, then actual. Reversing them can cause confusing error messages. - Comparing floating-point numbers directly can fail due to precision issues; use
assertEquals(expected, actual, delta)for a tolerance. - Not importing
assertEqualsstatically can require verbose calls.
java
/* Wrong order - confusing failure message */ assertEquals(actualValue, expectedValue); // Avoid this /* Correct order */ assertEquals(expectedValue, actualValue);
Quick Reference
| Usage | Description |
|---|---|
| assertEquals(expected, actual) | Checks if expected equals actual |
| assertEquals(message, expected, actual) | Same as above with custom failure message |
| assertEquals(expected, actual, delta) | For floating-point numbers with tolerance |
| assertEquals(message, expected, actual, delta) | Floating-point with message and tolerance |
Key Takeaways
Always put the expected value first and actual value second in assertEquals.
Use assertEquals to verify that your code returns the expected result.
Add a custom message to help identify failures quickly.
For floating-point comparisons, use the delta parameter to avoid precision errors.
Import assertEquals statically for cleaner test code.