我有一个 Vector3D
类,它具有 double 类型的属性 X
、Y
和 Z
(它还具有其他属性,例如 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/