Search code examples
c#unit-testingnfluent

NFluent library - List of List comparison


I have problem checking equality of List of List using 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
}

Problem: Last two checks fail.

Cause: The problem is that ContainsExactly does compare lists by reference (like Equals), not value by value (like SequenceEqual do).

Workarounds:

  1. Use XUnit Assert.Equal() which handles sequences correctely.
  2. Write custom subclass of List that implements Equals() using Enumerable.SequenceEqual

Question: I'd like to keep using NFluent, is there some easy way to make last two Checks working?


Solution

  • Short answer: upgrade to NFluent 2.1+, comparison behaviour has been revised.