我再一次难以获得FluentAssertions Should().BeEquivalentTo
的可定制方面来完成我要做的事情。当前的问题是近似比较字典值。我该如何使用BeEquivalentTo
选项使该测试通过:
[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
可以正常工作,但是为了完成我将其包括在这里:
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);
}