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

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.

Was this post helpful?

Leave a Reply

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