0
0
JUnittesting~10 mins

assertSame and assertNotSame in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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");
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Assign String 'hello' to variable aVariable a references String object "hello"-PASS
3Assign variable b to reference the same object as aVariable b references the same String object as a-PASS
4Create new String object with value 'hello' and assign to cVariable c references a new String object with value "hello"-PASS
5assertSame(a, b) checks if a and b reference the same objecta and b reference the same String objectassertSame passes because references are identicalPASS
6assertNotSame(a, c) checks if a and c reference different objectsa and c reference different String objectsassertNotSame passes because references are differentPASS
7Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: assertSame fails if the two references do not point to the same object, or assertNotSame fails if the two references point to the same object
Execution Trace Quiz - 3 Questions
Test your understanding
What does assertSame verify in this test?
AThat two variables have equal values
BThat two variables point to the exact same object
CThat two variables are not null
DThat two variables are different objects
Key Result
Use assertSame to verify two variables point to the exact same object in memory, not just equal values. Use assertNotSame to confirm they are different objects. This helps catch subtle bugs related to object identity.