Why assertEquals and assertSame in junit return the same result for two instances same class?

rawData picture rawData · Feb 11, 2015 · Viewed 54.1k times · Source

According to documentation

assertEquals() Asserts that two objects are equal.

assertSame() Asserts that two objects refer to the same object.

So I am expecting that if I have a class like below

class SomeClass {}

then

SomeClass someClass1= new SomeClass();
SomeClass someClass2= new SomeClass();
assertSame(someClass1,someClass2); // fail
assertEquals(someClass1,someClass2); // fail

the assertEquals should pass and assertSame should fail, as the value of both classes are equal but they have different reference location.

As I get failure in both cases then my question is what are the difference between these two ?

Answer

Alexis C. picture Alexis C. · Feb 11, 2015

Since you didn't override equals in your class, assertEquals behaves the same as assertSame since the default equals implementation compare references.

150    public boolean equals(Object obj) {
151        return (this == obj);
152    }

If you provide a dumb overriding of equals:

class SomeClass {
    @Override 
    public boolean equals(Object o) {
        return true;
    }
}

you'll see that assertEquals succeeds.