首页 > 解决方案 > 流利的断言:大致比较字典值

问题描述

我再一次难以让 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);
}

标签: c#unit-testingdictionaryfluent-assertions

解决方案


推荐阅读