0
0
JUnittesting~3 mins

Why assertSame and assertNotSame in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple check can save hours of confusion and catch hidden bugs!

The Scenario

Imagine you are checking if two boxes contain the exact same toy by opening them and comparing each toy piece manually.

The Problem

This manual checking is slow and confusing because toys might look the same but be different pieces. You might miss subtle differences or waste time comparing things that are actually different objects.

The Solution

Using assertSame and assertNotSame in tests lets you quickly check if two variables point to the exact same object or not, without guessing or comparing details manually.

Before vs After
Before
if (obj1 == obj2) {
  System.out.println("Same object");
} else {
  System.out.println("Different objects");
}
After
assertSame(obj1, obj2);
assertNotSame(obj1, obj3);
What It Enables

It enables fast and precise verification of object identity, catching subtle bugs that normal equality checks might miss.

Real Life Example

When testing a cache system, you want to confirm that the same cached object is returned each time, not just an equal copy. assertSame helps verify this behavior.

Key Takeaways

assertSame checks if two references point to the exact same object.

assertNotSame confirms two references are different objects.

These assertions save time and avoid errors compared to manual identity checks.