【问题标题】:Fluent Assertions: Approximately compare the properties of objects stored in ListsFluent Assertions:大致比较 Lists 中存储的对象的属性
【发布时间】:2016-08-30 13:57:45
【问题描述】:

这个问题建立在我之前问过的一个基础之上:

Fluent Assertions: Approximately compare a classes properties

如果我有课,说 Vector3

public class Vector3
{
    public double X { get; }
    public double Y { get; }
    public double Z { get; }

    public Vector3(double x, double y, double z)
    {
        this.X = x;
        this.Y = y;
        this.Z = z;
    }
}

而且组成了两个列表,如何近似比较两个列表中Vector3对象的属性,看是否相同。这就是我目前所拥有的(我使用的是 xUnit 框架,但这应该没什么区别):

public double precision = 1e-5;

[Fact]
public void ApproximatelyCompareVector3List()
{
    // Arrange
    var expectedList = new List<Vector3>
    {
        new Vector3(0.5, 1, 3),
        new Vector3(0, 2, 4)
    };

    // Act
    var calculatedList = List<Vector3>
    {
        new Vector3(0.4999999, 1.0000001, 3),
        new Vector3(0.0000001, 2.0000001, 4)
    };

    //Assert
    calculatedList.ShouldBeEquivalentTo(expectedList, options => options
        .Using<double>(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, precision))
        .When(info => info.SelectedMemberPath == "X" ||
                      info.SelectedMemberPath == "Y" ||
                      info.SelectedMemberPath == "Z" ));
}

但是,这似乎跳过了近似测试并需要精确排序。是否可以有确切的排序或任何排序来近似比较列表中包含的对象的属性?

【问题讨论】:

    标签: c# unit-testing fluent-assertions


    【解决方案1】:

    我知道这是一个有点老的问题,但无论如何,如果有人偶然发现同样的问题:
    Using&lt;double&gt;里面的代码没有被执行,因为选择的成员路径比较错误。您正在比较列表,这就是为什么路径看起来像 [0].X

    所以你可以修复它:

    .When(info => info.SelectedMemberPath.EndsWith("X") ||
                      info.SelectedMemberPath.EndsWith("Y") ||
                      info.SelectedMemberPath.EndsWith("Z")));
    

    或者只是:

    .WhenTypeIs<double>());
    

    ShouldBeEquivalentTo 默认情况下不需要精确排序。

    【讨论】:

    • 在包含所有属性时有效,但可以修改 When 以便仅比较选定的属性。例如,如果我只想大致比较两个列表中的 XZ 而不是 Y
    • 好的,所以使用.When(info =&gt; info.SelectedMemberPath.EndsWith("X") || info.SelectedMemberPath.EndsWith("Z"));
    • 我试过了,但测试失败了:预期项目[0].Y 为 1,但找到 1.0000001。预期 item[1].Y 为 2,但找到 2.0000001。预期 item[2].Y 为 0,但发现 -1E-07。 所以它似乎没有忽略Y,它仍在检查它而不使用近似。
    • 使用When,您可以定义要大致比较的成员。如果您想大致比较Y,则应将其包含在表达式.When(info =&gt; info.SelectedMemberPath.EndsWith("Y"));
    • 我想我明白了,我必须专门包含我想要的属性,或者排除我不想要的属性;使用 IncludingExcluding 扩展。否则会自动包含所有属性。
    猜你喜欢
    • 2016-08-15
    • 2016-07-31
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2012-04-10
    • 2013-07-08
    相关资源
    最近更新 更多