0
0
JUnittesting~15 mins

assertSame and assertNotSame in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify assertSame and assertNotSame behavior in JUnit
Preconditions (2)
Step 1: Create two variables referencing the same object instance
Step 2: Use assertSame to verify both variables point to the same object
Step 3: Create two variables referencing different object instances with same content
Step 4: Use assertNotSame to verify these variables do not point to the same object
✅ Expected Result: assertSame passes when both variables reference the same object; assertNotSame passes when variables reference different objects
Automation Requirements - JUnit 5
Assertions Needed:
assertSame to check two references point to the same object
assertNotSame to check two references point to different objects
Best Practices:
Use descriptive variable names
Keep tests independent and focused
Use @Test annotation for test methods
Use meaningful assertion messages
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Using assertEquals instead of assertSame to check object identity
Using assertSame on two different objects with same content
Not providing assertion messages
Bonus Challenge

Now add data-driven testing with 3 different object pairs to verify assertSame and assertNotSame

Show Hint