【问题标题】:Fluent Assertions: Approximately compare a classes propertiesFluent Assertions:大致比较一个类的属性
【发布时间】:2016-08-15 10:39:40
【问题描述】:

我有一个类 Vector3D,它具有 double 类型的属性 XYZ(它还具有其他属性,例如 Magnitude)。

使用 Fluent Assertions 在给定精度下大致比较所有属性或选择的属性的最佳方法是什么?

目前我一直是这样的:

calculated.X.Should().BeApproximately(expected.X, precision);
calculated.Y.Should().BeApproximately(expected.Y, precision);
calculated.Z.Should().BeApproximately(expected.Z, precision);

是否有单行方法可以实现相同的目标?比如使用ShouldBeEquivalentTo,或者这是否需要构造一个允许包含/排除属性的通用扩展方法?

【问题讨论】:

    标签: c# unit-testing fluent-assertions


    【解决方案1】:

    是的,可以使用ShouldBeEquivalentTo。以下代码将检查精度为 0.1 的所有 double 类型的属性:

    double precision = 0.1;
    calculated.ShouldBeEquivalentTo(expected, options => options
        .Using<double>(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, precision))
        .WhenTypeIs<double>());
    

    如果您只想比较 X、Y 和 Z 属性,请更改 When 约束,如下所示:

    double precision = 0.1;
    calculated.ShouldBeEquivalentTo(b, options => options
        .Using<double>(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, precision))
        .When(info => info.SelectedMemberPath == "X" ||
                      info.SelectedMemberPath == "Y" ||
                      info.SelectedMemberPath == "Z"));
    

    另一种方法是明确告诉 FluentAssertions 应该比较哪些属性,但它有点不那么优雅:

    double precision = 0.1;
    calculated.ShouldBeEquivalentTo(b, options => options
        .Including(info => info.SelectedMemberPath == "X" ||
                           info.SelectedMemberPath == "Y" ||
                           info.SelectedMemberPath == "Z")
        .Using<double>(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, precision))
        .When(info => true));
    

    由于Using 语句不返回EquivalencyAssertionOptions&lt;T&gt;,我们需要通过使用始终为真表达式调用When 语句来破解它。

    【讨论】:

    • 这很好。所以在这种特殊情况下必须使用.When 而不是.Including 来指定哪些属性用于等价测试?
    • Including 是明确告诉 FluentAssertions 在比较期间要使用的属性。我已经用解释更新了我的答案。
    • 我猜这是一个偏好问题,但是使用.Including(info =&gt; info.X).Including(info =&gt; info.Y).Including(info =&gt; info.Z) 而不是info.SelectedMemberPath == "X"... 有什么缺点吗?
    • 您指向的重载允许您在编译时检查表达式的正确性,但它有点冗长。
    • 非常有帮助的答案!如果 double 也可以为空,是否有解决方案?
    猜你喜欢
    • 2016-08-30
    • 2016-07-31
    • 2015-01-07
    • 2021-03-20
    • 2022-01-03
    • 2018-02-22
    • 2020-05-08
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多