Table of Contents
Junit 5’s org.junit.jupiter.Assertions class provides different static assertions method to write test cases.
Assertions.assertNotSame() checks whether expected and actual object refer to different objects. In case, both refer to same object, it will through AssertError.
public static void assertNotSame(Object expected,Object actual,String message)
public static void assertNotSame(Object expected,Object actual,Supplier messageSupplier)
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 AssertNotSameTest { /* * Examples for each overloaded methods of assertNotSame */ //public static void assertNotSame(Object expected, Object actual) @Test public void test1(){ String str1="Apple"; String str2="Apple"; Assertions.assertNotSame(str1,str2); } //public static void assertNotSame(Object expected, Object actual, String message) @Test public void test2(){ String str1=new String("Apple"); String str2=new String("Apple"); Assertions.assertNotSame(str1,str2,"str1 and str2 refer to same object"); } //public static void assertNotSame(Object expected, Object actual, Supplier messageSupplier) @Test public void test3(){ String str1=new String("Apple"); String str2=str1; Assertions.assertNotSame(str1,str2,() -> "str1 and str2 refer to same object"); } } |
When you run above testcase, you will get below output:
Let’s understand output of each testcase:
test1 – Fail
As str1 and str2 refer to same string literal, this testcase will fail. If you are confused with this, please refer String interview questions.
test2 – Pass
As str1 and str2 both refer to two different new String objects, this testcase will pass.
test3 – Fail
As str1 refer to new object and str2 refer to same String object(str2=str1), this testcase will fail.
That’s all about Assertions.assertNotSame() method.