流畅断言:近似比较类属性

Ayb*_*btu 12 c# unit-testing fluent-assertions

我有一个类Vector3D具有的属性X,YZ类型的双(它也有其它性能如Magnitude).

使用Fluent Assertions以给定精度近似比较所有属性或属性选择的最佳方法是什么?

目前我一直在这样做:

calculated.X.Should().BeApproximately(expected.X, precision);
calculated.Y.Should().BeApproximately(expected.Y, precision);
calculated.Z.Should().BeApproximately(expected.Z, precision);
Run Code Online (Sandbox Code Playgroud)

是否有单线方法可以实现相同的目标?比如使用ShouldBeEquivalentTo,或者这是否需要构建允许包含/排除属性的通用扩展方法?

Fab*_*NET 17

是的,可以使用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>());
Run Code Online (Sandbox Code Playgroud)

如果只想比较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"));
Run Code Online (Sandbox Code Playgroud)

另一种方法是明确告诉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));
Run Code Online (Sandbox Code Playgroud)

由于Using语句没有返回,EquivalencyAssertionOptions<T>我们需要通过When使用始终为true的表达式调用语句来破解它.