0
0
JUnittesting~5 mins

assertSame and assertNotSame in JUnit

Choose your learning style9 modes available
Introduction

We use assertSame and assertNotSame to check if two things are exactly the same object or not. This helps us make sure our program uses the right objects.

When you want to check if two variables point to the exact same object in memory.
When you want to confirm that two objects are not the same instance, even if they look similar.
When testing if a method returns the same object it was given or a new one.
When you want to avoid accidental duplication of objects in your code.
When verifying singleton patterns where only one instance should exist.
Syntax
JUnit
assertSame(expected, actual);
assertNotSame(unexpected, actual);

assertSame checks if both references point to the same object.

assertNotSame checks if both references point to different objects.

Examples
Passes if obj1 and obj2 are the same object.
JUnit
assertSame(obj1, obj2);
Passes if obj1 and obj3 are different objects.
JUnit
assertNotSame(obj1, obj3);
Passes because both are null, which counts as the same.
JUnit
assertSame(null, null);
Passes if obj1 is not null.
JUnit
assertNotSame(obj1, null);
Sample Program

This test class shows four tests:

  • testSameObjects passes because both variables point to the same string object.
  • testDifferentObjects passes because two different string objects with the same content are not the same object.
  • testFailSame fails because it expects two different objects to be the same.
  • testFailNotSame fails because it expects two references to the same object to be different.
JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class AssertSameTest {

    @Test
    void testSameObjects() {
        String a = "hello";
        String b = a;
        assertSame(a, b); // should pass
    }

    @Test
    void testDifferentObjects() {
        String a = new String("hello");
        String b = new String("hello");
        assertNotSame(a, b); // should pass
    }

    @Test
    void testFailSame() {
        String a = new String("test");
        String b = new String("test");
        assertSame(a, b); // should fail
    }

    @Test
    void testFailNotSame() {
        String a = "world";
        String b = a;
        assertNotSame(a, b); // should fail
    }
}
OutputSuccess
Important Notes

Remember, assertSame checks object identity, not equality of content.

Strings created with new String() are different objects even if they have the same text.

Using assertSame with null values passes only if both are null.

Summary

assertSame checks if two references point to the exact same object.

assertNotSame checks if two references point to different objects.

Use these to test object identity, not just if objects look equal.