JUnit Assert.assertSame() Method Example

In this post, we will demonstrate how to use Assert.assertSame() method with an example.
Check out JUnit 5 tutorials and examples at JUnit 5 Tutorial
In JUnit 5all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.

When to use assertSame() method

When we want to assert that the expected and the actual refer to the same Object, we must use the assertSame assertion.

Assert.assertSame(Object expected, Object actual) method

Asserts that two objects refer to the same object. If they are not the same, an AssertionError without a message is thrown. Parameters:
  • expected - the expected object
  • actual - the object to compare to expected

Assert.assertSame() method example

The below example demonstrates that how to use the assertSame() method to check Map contains the same values for the same keys:
import static org.junit.Assert.assertSame;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class AssertSameExample {
    private String processMap(final String key){
        final Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        map.put("key4", "value4");
        map.put("key5", "value5");
        map.put("key6", "value6");
        map.put("key7", "value7");
        map.put("key8", "value8");
        return map.get(key);
    public void checkSameReferenceTest(){
        final AssertSameExample example = new AssertSameExample(); 
        assertSame(example.processMap("key1"), example.processMap("key1"));