Table of Contents
Junit 5’s org.junit.jupiter.Assertions class provides different static assertions method to write test cases.
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,String message)
public static void assertSame(Object expected,Object actual,Supplier
Here is simple example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
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<String> 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:
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.