Search code examples
c#listunit-testingprecisionfluent-assertions

Comparing lists of objects with double property with FluentAssertions (C#)


I am trying to compare two list of objects with FluentAssertions. The objects have a property stored as a double that may be off by a small amount. Is there an efficient way to do this without iterating through the lists? My current method looks like

actualList.ShouldAllBeEquivalentTo(expectedList, options => options.Excluding(o => o.DoubleProperty));

for (var i = 0; i < actualList.Count; i++)
{
    actualList[i].DoubleProperty
                 .Should().BeApproximately(expectedList[i].DoubleProperty, precision);
}

Which is a little ugly and irritating as this issue keeps on coming up. Another possibility (inspired by Fluent Assertions: Compare two numeric collections approximately) is

actualList.Select(o => o.DoubleProperty)
          .Should().Equal(expectedList.Select(o => o.DoubleProperty),
                          (left, right) => AreEqualApproximately(left, right, precision));

Where I would write the AreEqualApproximately function myself. If possible, I would like to do the comparison without defining my own helper methods or iterating through the lists by index.


Solution

  • The following should also work using the options available in ShouldAllBeEquivalentTo

    actualList.ShouldAllBeEquivalentTo(expectedList, options => options
        .Using<double>(ctx => ctx.Subject.Should()
                                 .BeApproximately(ctx.Expectation, precision))
        .When(o => o.SelectedMemberPath == "DoubleProperty"));