Test Overview
This test checks if two object references point to the exact same object using assertSame, and verifies that two references do not point to the same object using assertNotSame.
This test checks if two object references point to the exact same object using assertSame, and verifies that two references do not point to the same object using assertNotSame.
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class ReferenceTest { @Test void testAssertSameAndNotSame() { String a = "hello"; String b = a; String c = new String("hello"); // assertSame passes because a and b refer to the same object assertSame(a, b, "a and b should be the same object"); // assertNotSame passes because a and c are different objects assertNotSame(a, c, "a and c should not be the same object"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | — | PASS |
| 2 | Assign String 'hello' to variable a | Variable a references String object "hello" | — | PASS |
| 3 | Assign variable b to reference the same object as a | Variable b references the same String object as a | — | PASS |
| 4 | Create new String object with value 'hello' and assign to c | Variable c references a new String object with value "hello" | — | PASS |
| 5 | assertSame(a, b) checks if a and b reference the same object | a and b reference the same String object | assertSame passes because references are identical | PASS |
| 6 | assertNotSame(a, c) checks if a and c reference different objects | a and c reference different String objects | assertNotSame passes because references are different | PASS |
| 7 | Test ends successfully | All assertions passed | — | PASS |
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