assertEquals vs assertSame

Difference between assertEquals and assertSame in JUnit

Chaanakya
Javarevisited
2 min readJan 16, 2023

--

assertEquals

Asserts that the expected and actual objects are equal.

It uses the equals() method to verify if objects are equal. For primitives, it uses the equality operator.

Below is the code from JUnit 5:

// code from Junit for objects
static boolean objectsAreEqual(Object obj1, Object obj2) {
if (obj1 == null) {
return obj2 == null;
} else {
return obj1.equals(obj2);
}
}

// code from Junit for primitives
static void assertEquals(int expected, int actual, String message) {
if (expected != actual) {
AssertionUtils.failNotEqual(expected, actual, message);
}
}

assertSame

Asserts that the expected and actual refer to the same object.

It uses the equality operator to verify that both actual and expected are pointing to the same object.

Below is the code from JUnit 5:

static void assertSame(Object expected, Object actual, String message) {
if (expected != actual) {
failNotSame(expected, actual, message);
}
}

Example

class TestAssertEqualsAndSame {

@Test
void testAssertEquals() {
assertEquals("1", "1"); // assertion will pass
assertEquals("1", new String("1")); // assertion will pass
assertEquals(new String("1"), new String("1")); // assertion will pass
}

@Test
void testAssertSame() {
// assertion will pass
assertSame("1", "1");

/*
assertion will fail because the references of both objects are different.
new String("<your string>") will create a new object
*/
assertSame("1", new String("1"));

// assertion will fail because the references of both objects are different
assertSame(new String("1"), new String("1"));
}
}

Feel free to ask any questions or share any comments you have about the article.

--

--