Search code examples
c#unit-testingnunitfluent-assertions

FluentAssertions: equivalence of sorted lists


I'm trying to establish equivalence of two lists using FluentAssertions in C#, where two things are of importance:

  1. the elements are compared by the values they hold, not by reference (i.e. they are equivalent, not equal)
  2. the order of the elements in the lists is important

Is there no function in FluentAssertions (or even NUnit) that does this?

Cheers!


Solution

  • By default, ShouldBeEquivalentTo() will ignore the order in the collections because in most cases two collections are equivalent if they contain the same items in any order. If you do care about the order, just use one of the overloads of WithStrictOrdering() on the options => parameter.

    Example:

    var myList = Enumerable.Range(1, 5);
    var expected = new[]
    {
        1, 2, 3, 4, 5
    };
    
    //succeeds
    myList.ShouldBeEquivalentTo(expected, options => options.WithStrictOrdering());
    
    //fails
    myList.Reverse().ShouldBeEquivalentTo(expected, options => options.WithStrictOrdering());
    

    Read more about these options in the documentation.