Verify that two different strings are not equal using assertNotEquals
Preconditions (2)
✅ Expected Result: The test passes because the two strings are different
import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; public class AssertNotEqualsTest { @Test void testStringsAreNotEqual() { String first = "Hello"; String second = "World"; assertNotEquals(first, second, "Strings should not be equal"); } }
This test class uses JUnit 5. We import assertNotEquals statically for cleaner code. The test method testStringsAreNotEqual creates two different strings, first and second. Then it calls assertNotEquals to check they are not the same. If they are different, the test passes. The message helps explain the assertion if it fails.
Now add data-driven testing with 3 different pairs of strings to verify assertNotEquals works for all
assertNotEquals check in a test?assertNotEqualsassertEquals which checks equality, assertNotEquals ensures values differ.assertNotEquals means values differ [OK]assertNotEquals can take two values and an optional message as the last parameter.int a = 3;
int b = 3;
assertNotEquals(a, b);
a and b are assigned the value 3, so they are equal.assertNotEquals expects the two values to be different. Since they are equal, the assertion fails and the test fails.String expected = "hello";
String actual = "hello";
assertNotEquals(expected, actual);
expected and actual hold the string "hello", so they are equal.generateId() never returns the value 0. Which JUnit assertion using assertNotEquals correctly tests this with 0 as the first argument and a custom message?generateId(). Adding a message helps explain failure.assertNotEquals(0, generateId(), "ID should not be zero"). assertNotEquals(generateId(), 0); misses the message and reverses parameters. assertNotEquals(0, 0, "ID should not be zero"); compares 0 to 0, which always fails. assertNotEquals("0", generateId()); compares string "0" to int, which is incorrect.Pass the test and this pattern moves unknown