Should one override equals method for asserting th

2019-01-14 16:37发布

问题:

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

回答1:

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.


回答2:

If you're testing the return value of a method or function that returns a value object (say, a currency value, or a tuple or map), then it makes sense to check that the result object is equal to an expected result object. In this case, the standard implementation of equals should do what you want.

Meanwhile, if you're calling a mutator on some object and then checking that it mutated the object as expected, I think it'd make more sense to check only those properties of the objects that ought to have been changed. This prevents you from having to make a custom definition of equals, which anyway would obscure what you expected to have happened in the test.



回答3:

I don't think this question has anything to do with a standard way of doing things. It's a matter of thinking about what your test is supposed to be testing.

If you want to test that all the properties are equal, assert the equality of all the properties.

If you want to test the return value of the whole object's Equals method, assert that instead.