JUnit Assert.assertNotSame() Method Example

assertNotSame() method belongs to JUnit 4 org.junit.Assert class. In JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.

void org.junit.Assert.assertNotSame(Object unexpected, Object actual)

Asserts that two objects do not refer to the same object. If they do refer to the same object, an AssertionError without a message is thrown. 
Parameters:
  • unexpected - the object you don't expect
  • actual - the object to compare to unexpected

Assert.assertNotSame(Object unexpected, Object actual) Method Example

import static org.junit.Assert.assertNotSame;

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

import org.junit.Test;

public class AssertNotSameExample {
 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 AssertNotSameExample example = new AssertNotSameExample(); 
        assertNotSame(example.processMap("key1"), example.processMap("key2"));
    }
}

Output:

Comments