JUnit assertNotSame 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.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)
public static void assertNotSame(Object expected,Object actual,String message)
public static void assertNotSame(Object expected,Object actual,Supplier messageSupplier)

Here is simple example

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

AssertNotSameTestOutput

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.

Was this post helpful?

Leave a Reply

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