我有一个类Vector3D
,其类型为X
,Y
和Z
类型为double(它还有其他属性,例如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
,或者这是否需要构建允许包含/排除属性的通用扩展方法?
答案 0 :(得分:8)
是的,可以使用ShouldBeEquivalentTo。以下代码将检查所有属性为double的属性,精度为0.1:
double precision = 0.1;
calculated.ShouldBeEquivalentTo(expected, option => 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
语句来破解它。