rawData rawData - 1 month ago 4
Java Question

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

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 {}


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

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

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


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 {
    public boolean equals(Object o) {
        return true;

you'll see that assertEquals succeeds.