assertEquals, assertTrue, and assertSame are JUnit assertion methods that check different kinds of conditions: value equality, a boolean condition, and object identity, respectively.
Key Points: • assertEquals(expected, actual) uses equals() to check that two values or objects are logically equal. • assertTrue(condition) simply verifies that a boolean expression evaluates to true. • assertSame(expected, actual) checks reference equality (==), confirming both variables point to the exact same object in memory. • assertEquals is by far the most commonly used, since most test assertions compare expected versus actual values. • Using assertSame instead of assertEquals by mistake can cause tests to fail even when two objects are logically equal but are different instances.
Example: Two separate new String("test") instances would pass assertEquals but fail assertSame, since they're equal in content but not the same object reference.
Code Example:
assertEquals(5, calculator.add(2, 3));
assertTrue(user.isActive());
assertSame(cachedUser, userCache.get(1L));Interview Tip: A concise interview answer is:
"assertEquals checks logical equality via equals(), assertTrue checks that a boolean condition holds, and assertSame checks that two references point to the exact same object using ==. I use assertSame specifically when identity matters, like verifying a cache returns the same instance rather than an equal copy."