How to Use assertNotEquals in JUnit for Testing
Use
assertNotEquals(expected, actual) in JUnit to check that two values are not the same. If the values are equal, the test fails; otherwise, it passes. This helps verify that your code does not produce unwanted equal results.Syntax
The assertNotEquals method in JUnit has the following syntax:
assertNotEquals(expected, actual): Checks thatexpectedandactualare not equal.assertNotEquals(message, expected, actual): Same as above but showsmessageif the assertion fails.
If expected.equals(actual) returns true, the assertion fails and the test stops.
java
assertNotEquals(expected, actual);
assertNotEquals("Values should not be equal", expected, actual);Example
This example shows how to use assertNotEquals in a JUnit 5 test to verify two strings are not equal.
java
import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; public class SampleTest { @Test void testStringsAreNotEqual() { String expected = "Hello"; String actual = "World"; assertNotEquals(expected, actual, "Strings should not be equal"); } }
Output
Test passed successfully with no errors.
Common Pitfalls
Common mistakes when using assertNotEquals include:
- Using it to check for equality instead of inequality.
- Comparing objects without proper
equals()method overridden, leading to unexpected results. - Confusing the order of parameters, though it does not affect the logic but may affect failure messages.
Always ensure the objects you compare have meaningful equality logic.
java
/* Wrong usage: expecting equality but using assertNotEquals */ // assertNotEquals("test", "test"); // This will fail /* Correct usage: */ assertNotEquals("test", "TEST"); // Passes because strings differ in case
Quick Reference
| Method | Description |
|---|---|
| assertNotEquals(expected, actual) | Fails if expected equals actual |
| assertNotEquals(message, expected, actual) | Fails with message if expected equals actual |
Key Takeaways
Use assertNotEquals to verify two values are not equal in your tests.
If the values are equal, assertNotEquals causes the test to fail.
Provide a failure message to make test results clearer.
Ensure objects compared have proper equals() implementation.
Do not confuse assertNotEquals with assertEquals.