I created a class and overridden the equals() method. When I use assertTrue(obj1.equals(obj2))
, it will pass the test; however, assertEquals(obj1, obj2)
will fail the test. Could someone please tell the reason why?
assertEquals. Asserts that two objects are equal. If they are not, an AssertionError is thrown with the given message. If expected and actual are null , they are considered equal.
assertEquals() calls equals() on your objects, and there is no way around that. What you can do is to implement something like public boolean like(MyClass b) in your class, in which you would compare whatever you want. Then, you could check the result using assertTrue(a. like(b)) .
assertEquals. Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null , they are considered equal.
Procedure assertEquals has two parameters, the expected-value and the computed-value, so a call looks like this: assertEquals(expected-value, computed-value);
My guess is that you haven't actually overridden equals
- that you've overloaded it instead. Use the @Override
annotation to find this sort of thing out at compile time.
In other words, I suspect you've got:
public boolean equals(MyClass other)
where you should have:
@Override // Force the compiler to check I'm really overriding something public boolean equals(Object other)
In your working assertion, you were no doubt calling the overloaded method as the compile-time type of obj1
and obj2
were both MyClass
(or whatever your class is called). JUnit's assertEquals
will only call equals(Object)
as it doesn't know any better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With