我试图断言一个对象与另一个对象“相等”。
这些对象只是一个类的实例,其中包含一组公共属性。有没有一种简单的方法可以让NUnit根据属性断言相等?
这是我目前的解决方案,但我认为可能有更好的解决方案:
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验证两个集合的内容是否相同。
发布于 2008-11-25 09:33:36
覆盖对象的.Equals,然后在单元测试中,您可以简单地执行以下操作:
Assert.AreEqual(LeftObject, RightObject);
当然,这可能意味着您只需要将所有单独的比较转移到.Equals方法,但它将允许您将该实现重用于多个测试,并且如果对象应该能够将自身与兄弟进行比较,这可能是有意义的。
发布于 2012-04-27 14:00:00
不要仅仅为了测试而重写Equals。它很单调乏味,而且会影响域逻辑。相反,
使用JSON比较对象的数据
您的对象上没有额外的逻辑。没有额外的测试任务。
只需使用这个简单的方法:
public static void AreEqualByJson(object expected, object actual)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var expectedJson = serializer.Serialize(expected);
var actualJson = serializer.Serialize(actual);
Assert.AreEqual(expectedJson, actualJson);
}
它似乎工作得很好。test runner结果信息将显示包含的JSON字符串比较(对象图),因此您可以直接看到错误所在。
还请注意!如果你有更大的复杂对象,并且只想比较它们的一部分,你可以(使用LINQ来获取序列数据)创建匿名对象来使用上面的方法。
public void SomeTest()
{
var expect = new { PropA = 12, PropB = 14 };
var sut = loc.Resolve<SomeSvc>();
var bigObjectResult = sut.Execute(); // This will return a big object with loads of properties
AssExt.AreEqualByJson(expect, new { bigObjectResult.PropA, bigObjectResult.PropB });
}
发布于 2008-11-25 09:38:01
如果出于任何原因无法重写Equals,您可以构建一个辅助方法,该方法通过反射遍历公共属性并断言每个属性。如下所示:
public static class AssertEx
{
public static void PropertyValuesAreEquals(object actual, object expected)
{
PropertyInfo[] properties = expected.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
object expectedValue = property.GetValue(expected, null);
object actualValue = property.GetValue(actual, null);
if (actualValue is IList)
AssertListsAreEquals(property, (IList)actualValue, (IList)expectedValue);
else if (!Equals(expectedValue, actualValue))
Assert.Fail("Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue);
}
}
private static void AssertListsAreEquals(PropertyInfo property, IList actualList, IList expectedList)
{
if (actualList.Count != expectedList.Count)
Assert.Fail("Property {0}.{1} does not match. Expected IList containing {2} elements but was IList containing {3} elements", property.PropertyType.Name, property.Name, expectedList.Count, actualList.Count);
for (int i = 0; i < actualList.Count; i++)
if (!Equals(actualList[i], expectedList[i]))
Assert.Fail("Property {0}.{1} does not match. Expected IList with element {1} equals to {2} but was IList with element {1} equals to {3}", property.PropertyType.Name, property.Name, expectedList[i], actualList[i]);
}
}
https://stackoverflow.com/questions/318210
复制相似问题