在单元测试中是否应该覆盖等于方法来断言对象相等? [英] Should one override equals method for asserting the object equality in a unit test?

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

问题描述

假设我们通过断言结果对象的所有属性与预期结果对象的属性相等来测试方法的结果.我们是否应该实现 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 for one use custom assertions. There are two main reasons:

  • 不要将测试问题强加到生产中.这意味着 equals 在测试方法中的含义可能与生产代码的含义不一致;
  • 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.

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

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