是的,可以使用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 语句来破解它。