Issue
I have a code which for the following
import static org.junit.Assert.assertEquals;
System.out.println("obj1 name = " + obj1.getName());
System.out.println("obj1 value = " + (obj1.getvalue() == null ? "null" : "not null"));
System.out.println("obj2 name = " + obj2.getName());
System.out.println("obj2 value = " + (obj2.getvalue() == null ? "null" : "not null"));
assertEquals(obj2, obj1);
yields
obj1 name = DC2
obj1 value = null
obj2 name = DC2
obj2 value = null
java.lang.AssertionError:
Expected :com.gms.contract.myClass.inventory.MyClass@795ce9b5
Actual :com.gms.contract.myClass.inventory.MyClass@280cb0b4
Isn't assertEquals suppose to compare by value?? It looks to me that it compares objects address. But maybe I am wrong?...
Solution
Isn't assertEquals suppose to compare by value??
No, it's supposed to compare using the equals
method.
You need to override equals
in MyClass
(and override hashCode
correspondingly).
It looks to me that it compares objects address.
No, that's simply the result of invoking toString()
on MyClass
, without you having overridden it. If you want something more meaningful to be shown, override toString()
too.
Answered By - Andy Turner