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

青春壹個敷衍的年華 提交于 2019-11-26 20:54:16

问题


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.



来源:https://stackoverflow.com/questions/1180044/should-one-override-equals-method-for-asserting-the-object-equality-in-a-unit-te

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!