在单元测试中,是否应该使用一个重写equals方法来声明对象相等? [英] Should one override equals method for asserting the object equality in a unit test?

查看:51
本文介绍了在单元测试中,是否应该使用一个重写equals方法来声明对象相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我们通过断言结果对象的所有属性与期望结果对象的属性相等来测试方法的结果.我们是否应该实现equals方法并使用Assert.AreEqual(expectedResult,ActualResult)...但equals可能意味着生产代码中有所不同.

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.

哪种是最佳做法?

  • 通过覆盖的equals方法声明对象的相等性

  • 声明所有属性的相等性

推荐答案

I一使用自定义断言.主要有两个原因:

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

  • 不要将测试问题强制投入生产.这意味着测试方法中equals的含义可能与生产代码的含义不一致;
  • 对于所有测试而言,
  • 相等值可能不够好.不同的测试将需要不同的断言,因此无论如何您最终都将使用自定义断言.
  • 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.

这篇关于在单元测试中,是否应该使用一个重写equals方法来声明对象相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆