c# - 使用 XUnit Assert 函数比较两个 List<T>

标签 c# assert xunit xunit.net xunit2

以下未使用 XUnit 断言为真(StartDate 和 EndDate 是 DatePeriod 仅有的两个公共(public)属性):

var actual = new List<DatePeriod>()
{
    new DatePeriod() { StartDate = new DateTime(2017, 1, 20), EndDate = new DateTime(2018, 1, 19)},
    new DatePeriod() { StartDate = new DateTime(2018, 1, 20), EndDate = new DateTime(2018, 3, 31)}
};

var expected = new List<DatePeriod>()
{
    new DatePeriod() { StartDate = new DateTime(2017, 1, 20), EndDate = new DateTime(2018, 1, 19)},
    new DatePeriod() { StartDate = new DateTime(2018, 1, 20), EndDate = new DateTime(2018, 3, 31)}
};

Assert.Equal(actual, expected);

根据一些研究,我预计在最新版本的 XUnit 中,这些最终会被认为是相等的,因为在使用 Assert 时,只要顺序与实际顺序相同。

最佳答案

您只需像这样覆盖 EqualsGetHashCode:

public class DatePeriod
{
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;

        DatePeriod other = (DatePeriod)obj;

        return StartDate.Equals(other.StartDate) && EndDate.Equals(other.EndDate);
    }

    public override int GetHashCode()
    {
        return new {StartDate, EndDate}.GetHashCode();
    }

    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

xUnit 在您可以调用 Assert.Equal 的意义上识别集合,而其他测试框架需要特殊方法,例如 CollectionAssert.AreEqual

在所有情况下,框架都会为列表中的每个项目调用 Equals,传递另一个列表中的相应项目。如果您有一个字符串或整数列表,则 Equals 默认情况下会正确实现。对于像 DatePeriod 这样的自定义对象,Equals 方法的默认实现是基于引用相等性,即两个对象是相等的,因为它们实际上是同一个对象。要获得基于值的相等性,您必须覆盖 Equals 方法(以及推荐的 GetHashCode 方法)。

关于c# - 使用 XUnit Assert 函数比较两个 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36267753/

相关文章:

C# : How to Upload File to a Specific Folder using Google Drive API v3 - Windows Console Application

c# - MSTest ThrowsException 与异常对象的条件?

c# - .Net 4.5.2 中 Debug.Assert(condition, interpolatedStringMessage) 的求值顺序

ruby - 向 Ruby 的内核类添加 assert() 方法是 Ruby 惯用的做法吗?

c# - F#:为什么这两个集合不相等?

javascript - Mocha 在完成所有测试之前结束测试运行

c# - 计算扩展数据数组平均数的公式

c# - 在 App.xaml 中添加不同的 BottomAppBars

c# - 下载/上传文件,过滤什么字符c#

c++ - 如何使用 Visual Studio 自动记录断言?