FluentAssertions for equality of objects graph with array - 近似相等

FluentAssertions for equality of objects graph with array - approximate equality

我正在尝试为 API 编写一组测试,结果 returns 的结果如下

{
  "metrics": [
    {
      "key": "Metric1",
      "portfolios": [
        {
          "portfolioKey": "Portfolio1",
          "outputs": [
            1000000,
            1013785.999689,
            1040271.12363882
          ]
        }
      ]
    },
    {
      "key": "Metric2",
      "portfolios": [
        {
          "portfolioKey": "Portfolio1",
          "outputs": [
            1000000,
            986601.99318665,
            985925.470917517
          ]
        }
      ]
    }
  ]
}

如您所见,返回的对象有

我要测试的实际上是这个嵌套的双精度数组,我需要比较给定 metric/portfolio 组合的输出。但是我只想测试 approximate 相等性。为了这个问题,假设我希望预期结果与 0.1

内的实际结果相匹配

我正在使用 Fluent Assertions,它在比较对象图方面有一些相当不错的 documentation,但我似乎无法正确配置它。

这是我的代码:

expectedMetrics.Should().BeEquivalentTo(actualMetrics, options =>
{
    options.Using<Metric>(m =>
    {
        m.Subject.Should().BeEquivalentTo(m.Subject, mo =>
        {
            mo.WithMapping<Metric>(x => x.Key, x => x.Key);
            mo.Using<Portfolio>(p =>
            {
                p.Should().BeEquivalentTo(p.Subject, po =>
                {
                    po.WithMapping<Portfolio>(x => x.PortfolioKey, x => x.PortfolioKey);
                    po.WithStrictOrderingFor(x => x.Outputs);
                    po.Including(x => x.Outputs).Using<double>(x =>
                    {
                        x.Subject.Should().BeApproximately(x.Expectation, 0.1);
                    });
                    return po;
                }); 
            });
            return mo;
        });
    });
    options.WithTracing();
    return options;
});

这似乎既没有使用我的映射,也没有使用我的双打近似相等。追踪的一小段摘录说

Expected expectedMetrics.Metrics[0].Portfolios[0].Outputs[1] to be 1013785.9996890002, but found 1013785.999689.
Expected expectedMetrics.Metrics[0].Portfolios[0].Outputs[2] to be 1040271.1236388228, but found 1040271.12363882.

这显然没有检查到 0.1 以内。我做错了什么?

您需要将 Using<double>()WhenTypeIs<double>() 配对。

var subject = new[] { 1013785.999689, 1040271.12363882 };
var expected = new[] { 1013785.9996890002, 1040271.1236388228 };

subject.Should().BeEquivalentTo(expected, opt => opt
    .Using<double>(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, 0.1))
    .WhenTypeIs<double>()
);

https://fluentassertions.com/objectgraphs/#equivalency-comparison-behavior