gpt4 book ai didi

c# - 如何用 NUnit 单元测试比较复杂对象

转载 作者:行者123 更新时间:2023-11-30 15:57:35 25 4
gpt4 key购买 nike

学习如何使用 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

关于c# - 如何用 NUnit 单元测试比较复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44825488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com