![](/img/trans.png)
[英]Fluent Assertions: Approximately compare the properties of objects stored in Lists
[英]Fluent Assertions: Approximately compare a classes properties
我有一个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
语句来破解它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.