Fluent Assertions: Approximately compare a classes properties

对着背影说爱祢 提交于 2019-12-01 15:43:33
Fabien PERRONNET

Yes it's possible using ShouldBeEquivalentTo. The following code will check all properties that are of type double with a precision of 0.1 :

double precision = 0.1;
calculated.ShouldBeEquivalentTo(expected, option => options
    .Using<double>(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, precision))
    .WhenTypeIs<double>());

If you want to compare only the X, Y and Z properties change the When constraint like this :

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"));

Another approach is to explicitly tell to FluentAssertions which properties should be compared, but it's a bit less elegant :

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));

Since the Using statement does not return a EquivalencyAssertionOptions<T> we need to hack it by calling the When statement with an always true expression.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!