其他分享
首页 > 其他分享> > CodeGo.net>如何比较复杂的对象与NUnit的单元测试

CodeGo.net>如何比较复杂的对象与NUnit的单元测试

作者:互联网

学习如何使用NUnit编写单元测试.

努力比较两个复杂的对象.

这里有一个非常相似的问题的答案Comparing Two objects using Assert.AreEqual(),尽管看起来您应该覆盖对象上的Equals()-考虑到可能有多少个对象(您想比较),这并不理想,更不用说了对象及其嵌套对象上可能存在的属性数.

给定示例对象:

   public class AMockObject
   {
       public int Id { get; set; }
       public ICollection<int> Numbers { get; set; }

       public AMockObject()
       {
          Numbers = new List<int>();
       }           
    }

我想比较一下此对象的两个单独实例具有相同的值,并且发现Assert.AreEqual()并没有真正实现我的预期.

例如,所有这些均失败:

// Example 1
AMockObject a = new AMockObject();
AMockObject b = new AMockObject();
Assert.AreEqual(a,b); // Fails - they're not equal

// Example 2
AMockObject a = new AMockObject() { Id = 1 };
AMockObject b = new AMockObject() { Id = 1 };
Assert.AreEqual(a, b); // Also fails

// Example 3
AMockObject a = new AMockObject() { Id = 1 };
a.Numbers.Add(1);
a.Numbers.Add(2);
a.Numbers.Add(3);    
AMockObject b = new AMockObject() { Id = 1 };
b.Numbers.Add(1);
b.Numbers.Add(2);
b.Numbers.Add(3);    
Assert.AreEqual(a, b); // also fails

我们有适当的代码在其中克隆各种对象,其中一些非常大.
鉴于这是很常见的事情,是否有同样通用的方法来测试两个对象在属性值级别上是否相同?

这里的示例有两个属性.在现实世界中,我有一个带有几十个属性的对象,其中一些是其他复杂对象的列表.

暂时,我正在序列化对象并比较字符串,尽管这感觉并不理想.

解决方法:

在单元测试中有一个称为Fluent Assertions的工具,它能够进行这种比较.

注意

Objects are equivalent when both object graphs have equally named
properties with the same value, irrespective of the type of those
objects. Two properties are also equal if one type can be converted to
another and the result is equal. The type of a collection property is
ignored as long as the collection implements
System.Collections.IEnumerable and all items in the collection are
structurally equal. Notice that actual behavior is determined by the
global defaults managed by FluentAssertions.AssertionOptions.

using FluentAssertions;

//...

// Example 1
AMockObject a = new AMockObject();
AMockObject b = new AMockObject();
a.ShouldBeEquivalentTo(b); // Asserts that an object is equivalent to another object.

// Example 2
AMockObject a = new AMockObject() { Id = 1 };
AMockObject b = new AMockObject() { Id = 1 };
a.ShouldBeEquivalentTo(b); //Asserts that an object is equivalent to another object.

// Example 3
AMockObject a = new AMockObject() { Id = 1 };
a.Numbers.Add(1);
a.Numbers.Add(2);
a.Numbers.Add(3);    
AMockObject b = new AMockObject() { Id = 1 };
b.Numbers.Add(1);
b.Numbers.Add(2);
b.Numbers.Add(3);
a.ShouldBeEquivalentTo(b)    
a.Numbers.ShouldAllBeEquivalentTo(b.Numbers); // Asserts that a collection of objects is equivalent to another collection of objects.

Documentation here

标签:unit-testing,nunit,c
来源: https://codeday.me/bug/20191111/2018309.html