NFluent 库 - 列表列表比较

NFluent library - List of List comparison

我在使用 NFluent:

检查列表列表的相等性时遇到问题
using NFluent;

[Fact]
public void CollectionTest()
{
    var a = new List<int> {1, 2};
    var b = new List<int> {3, 4};

    // List contains references to a and b
    var list1 = new List<List<int>> {a, b};
    Check.That(list1).ContainsExactly(a, b);  // OK
    Check.That(list1).ContainsExactly(new List<List<int>> {a, b});  // OK

    // List contains new instances of lists same as a and b
    var list2 = new List<List<int>>
    {
        new List<int> {1, 2}, // new instance, same as a
        new List<int> {3, 4}  // new instance, same as b
    };
    Assert.Equal(list2, new List<List<int>> { a, b });  // XUnit assert is OK
    Check.That(list2).ContainsExactly(a, b);  // Fail
    Check.That(list2).ContainsExactly(new List<List<int>> {a, b});  // Fail
}

问题: 最后两次检查失败。

原因: 问题是 ContainsExactly 确实按引用比较列表(如 Equals),而不是按值比较(如 SequenceEqual 做)。

解决方法:

  1. 使用可以正确处理序列的 XUnit Assert.Equal()
  2. 使用 Enumerable.SequenceEqual
  3. 编写实现 Equals() 的自定义列表子类

问题:我想继续使用 NFluent,有没有一些简单的方法可以使最后两个检查正常工作?

简答:升级到 NFluent 2.1+,比较行为已修改。