比较 NUnit 中两个对象之间的相等性 [英] Compare equality between two objects in NUnit

查看:47
本文介绍了比较 NUnit 中两个对象之间的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图断言一个对象与另一个对象相等".

I'm trying to assert that one object is "equal" to another object.

对象只是具有一堆公共属性的类的实例.有没有一种简单的方法可以让 NUnit 根据属性断言相等?

The objects are just instances of a class with a bunch of public properties. Is there an easy way to have NUnit assert equality based on the properties?

这是我目前的解决方案,但我认为可能有更好的方法:

This is my current solution but I think there may be something better:

Assert.AreEqual(LeftObject.Property1, RightObject.Property1)
Assert.AreEqual(LeftObject.Property2, RightObject.Property2)
Assert.AreEqual(LeftObject.Property3, RightObject.Property3)
...
Assert.AreEqual(LeftObject.PropertyN, RightObject.PropertyN)

我想要的将与 CollectionEquivalentConstraint 的精神相同,其中 NUnit 验证两个集合的内容是否相同.

What I'm going for would be in the same spirit as the CollectionEquivalentConstraint wherein NUnit verifies that the contents of two collections are identical.

推荐答案

为您的对象覆盖 .Equals,然后在单元测试中您可以简单地执行以下操作:

Override .Equals for your object and in the unit test you can then simply do this:

Assert.AreEqual(LeftObject, RightObject);

当然,这可能意味着您只需将所有单独的比较移动到 .Equals 方法,但它允许您对该实现重复使用多个测试,并且如果对象应该能够将自己与无论如何都是兄弟姐妹.

Of course, this might mean you just move all the individual comparisons to the .Equals method, but it would allow you to reuse that implementation for multiple tests, and probably makes sense to have if objects should be able to compare themselves with siblings anyway.

这篇关于比较 NUnit 中两个对象之间的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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