c# - 流利的断言 : Approximately compare a classes properties

标签 c# unit-testing fluent-assertions

我有一个 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,或者这是否需要构造一个允许包含/排除属性的通用扩展方法?

最佳答案

是的,可以使用 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<T>我们需要通过调用 When 来破解它表达式始终为 true 的语句。

关于c# - 流利的断言 : Approximately compare a classes properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36782975/

相关文章:

c# - 流利的断言 Should().Should().BeEquivalentTo 忽略被排除的成员

c# - 在特定运行时强制 MonoDevelop 为 'Run Tests'

java - 如何为 Junit 单元测试设置 JVM 参数?

c# - (什么时候)使用 FluentAssertions 是个好主意?

c# - modalpopupextender 设置为多个目标控件 ID?

c# - 对 SqlCommand 的扩展方法进行单元测试的方法

.net - FluentAssertions : check a list contains an object, 不包括属性

c# - 在 .net 中部署 Actions on Google 服务

C#:日期时间转换

c# - WFP 数据网格行详细信息垂直滚动条不起作用