Let's say we are testing the result of a method by asserting the equality of all the properties of the result object with properties of an expected result object. Should we implement equals method and use Assert.AreEqual(expectedResult, actualResult)... But equals may mean something different in production code.
Which is the best practice?
or
Why we override equals() method? It needs to be overridden if we want to check the objects based on the property. For example, we want to check the equality of employee object by the id. Then, we need to override the equals() method.
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)) .
You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.
AreEqual(Object, Object, String) Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
I for one use custom assertions. There are two main reasons:
equals
in a test method might not coincide with the meaning for production code;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