JUnit 5 assertSame Example

In this article, we will learn about assertSame() static method which belongs to JUnit 5 org.junit.jupiter.api.Assertions Class. Note that in JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.
There are many overloaded version of assertSame() methods present in org.junit.jupiter.api.Assertions class.
Let me list out tools and technologies that I have used to develop JUnit 5 assertSame Example.

Tools and Technologies Used

  1. Eclipse photon (only this eclipse version supports JUnit 5)
  2. Maven
  3. JUnit 5
  4. JDK 8 or later
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.

assertSame() Method Example

package com.javaguides.junit5.assertions;

import static org.junit.Assert.assertSame;

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

import org.junit.jupiter.api.Test;

public class JUnit5AssertSameExample {
  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);
    }
  
  @Test
     public void checkSameReferenceTest(){
         final JUnit5AssertSameExample example = new JUnit5AssertSameExample(); 
         assertSame(example.processMap("key1"), example.processMap("key1"));
     }
}

Output

Comments