Verify assertSame and assertNotSame behavior in JUnit
Preconditions (2)
✅ Expected Result: assertSame passes when both variables reference the same object; assertNotSame passes when variables reference different objects
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class AssertSameNotSameTest { @Test void testAssertSame() { String original = "JUnit"; String reference = original; assertSame(original, reference, "Both references should point to the same object"); } @Test void testAssertNotSame() { String first = new String("JUnit"); String second = new String("JUnit"); assertNotSame(first, second, "References should point to different objects even if content is same"); } }
The code imports JUnit 5 assertions and defines two test methods.
In testAssertSame, two variables point to the same String object. assertSame verifies they reference the exact same object.
In testAssertNotSame, two different String objects with the same content are created. assertNotSame verifies they are different objects in memory.
Each assertion includes a message to clarify the test intent if it fails.
Now add data-driven testing with 3 different object pairs to verify assertSame and assertNotSame
assertSame check in a JUnit test?assertSame checks if both references point to the exact same object in memory, not just equal content.assertEquals check if objects are equal in content, but assertSame checks identity.assertNotSame(expected, actual), both are objects to compare references.String a = "test";
String b = "test";
String c = new String("test");
assertSame(a, b);
assertNotSame(a, c);a and b point to the same string literal in the string pool, so assertSame(a, b) passes.c is a new String object created on the heap, different from a, so assertNotSame(a, c) passes.Object obj1 = new Object(); Object obj2 = obj1; assertNotSame(obj1, obj2);
assertNotSame expects different objects; since references are same, assertion fails.class Person {
String name;
Person(String name) { this.name = name; }
}
Person p1 = new Person("Alice");
Person p2 = new Person("Alice");
Person p3 = p1;
assertSame(p1, p3);
assertNotSame(p1, p2);assertSame(p1, p3) passes.assertNotSame(p1, p2) passes.Pass the test and this pattern moves unknown