Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one override equals method for asserting the object equality in a unit test?

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?

  • Asserting the equality of the objects through overriden equals method

or

  • Asserting the equality of all the properties
like image 669
spinodal Avatar asked Jul 24 '09 20:07

spinodal


People also ask

Why do we override equal method?

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.

How do you assert two objects are equal in Junit?

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)) .

Can equals method be overridden?

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.

How do you compare two objects using assert?

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.


1 Answers

I for one use custom assertions. There are two main reasons:

  • don't force test concerns into production. This means that the meaning of equals in a test method might not coincide with the meaning for production code;
  • equals may not be good enough for all the tests. Different tests will require different assertions, so you'll likely end up using custom assertions anyway.
like image 52
Robert Munteanu Avatar answered Sep 21 '22 17:09

Robert Munteanu