流利的断言:大约比较一个类的属性 [英] Fluent Assertions: Approximately compare a classes properties

查看:78
本文介绍了流利的断言:大约比较一个类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类Vector3D,它具有属性double类型的XYZ(它还具有其他属性,例如Magnitude).

I have a class Vector3D that has the properties X, Y and Z of type double (it also has other properties such as Magnitude).

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

What is the best way of approximately comparing all the properties or a selection of the properties at a given precision using Fluent Assertions?

目前,我一直在这样做:

Currently I have been doing it like this:

calculated.X.Should().BeApproximately(expected.X, precision);
calculated.Y.Should().BeApproximately(expected.Y, precision);
calculated.Z.Should().BeApproximately(expected.Z, precision);

是否有一种单行方法可以实现相同的目的?例如使用ShouldBeEquivalentTo,还是这需要构造一个通用的扩展方法以允许包含/排除属性?

Is there a single line approach that will achieve the same thing? Such as using ShouldBeEquivalentTo, or does this require constructing a generic extension method that allows properties to be included / excluded?

推荐答案

是的,可以使用

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

如果只想比较X,Y和Z属性,则可以这样更改While约束:

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

另一种方法是显式地告诉FluentAssertions应该比较哪些属性,但这并不那么优雅:

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

由于Using语句不返回EquivalencyAssertionOptions<T>,因此我们需要通过使用始终为true的表达式调用When语句来对其进行破解.

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.

这篇关于流利的断言:大约比较一个类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆