是否应该重写 equals 方法来在单元测试中断言对象相等?

发布于 2024-07-29 13:12:34 字数 249 浏览 2 评论 0原文

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

哪个是最佳实践?

  • 通过重写 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.

Which is the best practice?

  • Asserting the equality of the objects through overriden equals method

or

  • Asserting the equality of all the properties

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烧了回忆取暖 2024-08-05 13:12:34

我首先使用自定义断言。 有两个主要原因:

  • 不要将测试问题强行带入生产中。 这意味着测试方法中 equals 的含义可能与生产代码的含义不一致;
  • equals 可能不足以满足所有测试。 不同的测试将需要不同的断言,因此您最终可能会使用自定义断言。

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.
篱下浅笙歌 2024-08-05 13:12:34

如果您正在测试返回值对象(例如,货币值、元组或映射)的方法或函数的返回值,则检查结果对象是否等于预期结果对象是有意义的。 在这种情况下, equals 的标准实现应该满足您的要求。

同时,如果您在某个对象上调用变异器,然后检查它是否按预期变异了该对象,我认为仅检查应该更改的对象的那些属性会更有意义。 这可以防止您必须对 equals 进行自定义定义,无论如何,这都会掩盖您期望在测试中发生的情况。

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.

彻夜缠绵 2024-08-05 13:12:34

我认为这个问题与标准的做事方式没有任何关系。 这是一个思考你的测试应该测试什么的问题。

如果要测试所有属性是否相等,请断言所有属性相等。

如果您想测试整个对象的 Equals 方法的返回值,请改为断言。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文