I'm once again having difficulty getting the customisable aspects of FluentAssertions Should().BeEquivalentTo
to do what I'm after. The current problem is approximately comparing dictionary values. How would I go about getting this test to pass using the BeEquivalentTo
options:
[Fact]
public void SomeTest()
{
var dictOne = new Dictionary<string, double>
{
{ "a", 1.2345 },
{ "b", 2.4567 },
{ "c", 5.6789 },
{ "s", 3.333 }
};
var dictTwo = new Dictionary<string, double>
{
{ "a", 1.2348 },
{ "b", 2.4561 },
{ "c", 5.679 },
{ "s", 3.333 }
};
dictOne.Should().BeEquivalentTo(dictTwo, options => options
.Using<double>(ctx => ctx.ApproximatelyCompareDouble(1e-2))
.WhenTypeIs<KeyValuePair<string, double>>()
);
}
ApproximatelyCompareDouble
works correctly, but I've included it here for completion:
public static void ApproximatelyCompareDouble(this IAssertionContext<double> ctx, double precision)
{
var bothNaN = double.IsNaN(ctx.Subject) && double.IsNaN(ctx.Expectation);
var bothPositiveInf = double.IsPositiveInfinity(ctx.Subject) && double.IsPositiveInfinity(ctx.Expectation);
var bothNegativeInf = double.IsNegativeInfinity(ctx.Subject) && double.IsNegativeInfinity(ctx.Expectation);
var withinPrecision = Math.Abs(ctx.Subject - ctx.Expectation) <= precision;
Execute.Assertion
.BecauseOf(ctx.Because, ctx.BecauseArgs)
.ForCondition(bothNaN || bothPositiveInf || bothNegativeInf || withinPrecision)
.FailWith("Expected {context:double} to be {0} +/- {1} {reason}, but found {2}", ctx.Subject, precision, ctx.Expectation);
}