Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 218
Samuel Neugber Avatar asked Oct 10 '14 09:10

Samuel Neugber


4 Answers

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.

like image 76
Dennis Doomen Avatar answered Oct 21 '22 01:10

Dennis Doomen


Late to the game here but I use the Fluent Assertions version of this here:

actualRows.Should().BeEquivalentTo(expectedRows,options => options.WithStrictOrdering());

It will check all the values of all the properties for equivalence, and with this option, the order matters. If the order does not matter, omit the options param and it will make sure the item from one collection will exist somewhere in the other. Hope this helps someone

like image 15
Marc Ziss Avatar answered Oct 21 '22 01:10

Marc Ziss


I think you can just do:

myObject.List.SequenceEqual(myOtherObject.ListToCompare).Should().BeTrue();

This will only work if the elements in the list are equal when using Object.Equal(element1, element2)

if this is not the case then you need to implement your own EqualityComparer for the objedts in the lists then use:

myObject.List.SequenceEqual(myOtherObject.ListToCompare, myEqualityComparer)
             .Should().BeTrue();
like image 6
Sam Holder Avatar answered Oct 21 '22 02:10

Sam Holder


From this post.

The newer ShouldBeEquivalentTo() introduced in FA 2.0 is doing an in-depth structural comparison and also reporting on any differences

You can achieve it in this way.

actual.Should().BeEquivalentTo(expectation, c => c.WithStrictOrdering());
like image 3
Nguyễn Văn Phong Avatar answered Oct 21 '22 01:10

Nguyễn Văn Phong