In other words, does assertEquals works with a class that overrides equals
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.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y , this method returns true if and only if x and y refer to the same object ( x == y has the value true ).
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)) .
If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.
From the source code of the assertEquals method that you can find on the Junit GitHub Repo:
/** * Asserts that two objects are equal. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertEquals(String message, Object expected, Object actual) { if (expected == null && actual == null) { return; } if (expected != null && expected.equals(actual)) { return; } failNotEquals(message, expected, actual); }
You can see that Junit is using the .equals()
method.
Edit:
The code snippet is coming from a deprecated version of Junit.
You can read about the source of the 'new' Junit here. The idea is pretty much the same, the .equals()
method is also used.
does assertEquals works with a class that overrides equals?
Yes, assertEquals()
invokes the overridden equals()
if the class has one.
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