[wp-night-mode-button]

JUnit assertSame example

Junit 5’s org.junit.jupiter.Assertions class provides different static assertions method to write test cases.

Please note that you need to use JUnit’s org.junit.Assert class in case of JUnit 4 or JUnit 3 to assert using assertNull method.

Assertions.assertSame() checks whether expected and actual object refer to same object. In case, both do not refer to same object, it will through AssertError.

public static void assertSame(Object expected,Object actual)
public static void assertSame(Object expected,Object actual,String message)
public static void assertSame(Object expected,Object actual,Supplier messageSupplier)

Here is simple example

package org.arpit.java2blog;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
 
public class AssertSameTest {
 
    /*
     * Examples for each overloaded methods of assertSame
     */
    
    //public static void assertSame(Object expected, Object actual)
    @Test
    public void test1(){
    	String str1="India";
    	String str2="India";
    	Assertions.assertSame(str1,str2);
    }
    
    //public static void assertSame(Object expected, Object actual, String message)
    @Test
    public void test2(){
    	
    	String str1=new String("India");
    	String str2=new String("India");
    	Assertions.assertSame(str1,str2,"str1 and str2 do not refer to same object");
    }
    
    //public static void assertSame(Object expected, Object actual, Supplier messageSupplier)
    @Test
    public void test3(){
    	String str1=new String("India");
    	String str2=str1;
    	Assertions.assertSame(str1,str2,() -> "str1 and str2 do not refer to same object");
    }
}

When you run above testcase, you will get below output:
AssertSameTestOutput

Let’s understand output of each testcase:


test1 – Pass

As str1 and str2 refer to same string literal, this testcase will pass. If you are confused with this, please refer String interview questions.


test2 – Fail

As str1 and str2 both refer to two different new String objects, this testcase will fail.


test3 – Pass

As str1 refer to new object and str2 refer to same String object(str2=str1), this testcase will pass.


That’s all about Assertions.assertSame() method.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.