c# - 将具有双属性的对象列表与 FluentAssertions 进行比较 (C#)

标签 c# list unit-testing precision fluent-assertions

我正在尝试使用 FluentAssertions 比较两个对象列表。这些对象有一个存储为 double 型的属性,该属性可能会有少量偏差。有没有一种有效的方法可以在不迭代列表的情况下做到这一点?我当前的方法看起来像

actualList.ShouldAllBeEquivalentTo(expectedList, options => options.Excluding(o => o.DoubleProperty));

for (var i = 0; i < actualList.Count; i++)
{
    actualList[i].DoubleProperty
                 .Should().BeApproximately(expectedList[i].DoubleProperty, precision);
}

这有点丑陋且令人恼火,因为这个问题不断出现。另一种可能性(受到 Fluent Assertions: Compare two numeric collections approximately 的启发)是

actualList.Select(o => o.DoubleProperty)
          .Should().Equal(expectedList.Select(o => o.DoubleProperty),
                          (left, right) => AreEqualApproximately(left, right, precision));

我自己编写AreEqualApproximately 函数的位置。如果可能的话,我想在不定义自己的辅助方法或按索引迭代列表的情况下进行比较。

最佳答案

使用 ShouldAllBeEquivalentTo 中提供的选项,以下内容也应该有效

actualList.ShouldAllBeEquivalentTo(expectedList, options => options
    .Using<double>(ctx => ctx.Subject.Should()
                             .BeApproximately(ctx.Expectation, precision))
    .When(o => o.SelectedMemberPath == "DoubleProperty"));

关于c# - 将具有双属性的对象列表与 FluentAssertions 进行比较 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45242650/

相关文章:

c# - 使用Reactive Extensions模拟UIElement的点击

python - 如何在Python中对多个文件进行逐行排序?

C# 没有另一个列表元素的列表(集合论、补集)

python - 替换/删除字符串中的字符

c# - 使用 UnityAutoMoqContainer 注册通用接口(interface)

C# 应用程序 GUI 在不同的 Windows 图标/文本大小设置上中断

c# - 如何访问 GroupPrincipal 对象上的备注字段

unit-testing - 为什么在此D程序中无法进行单元测试?

c# - 使用 RabbitMQ 永不结束消息

c# - 当我向 Controller 添加新的依赖项时单元测试中断