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

放肆的年华 提交于 2019-11-27 22:07:41

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.

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.

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.

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