首页 > 解决方案 > xUnit 断言两个值相等且具有一定的容差

问题描述

我正在尝试将两个数字的精度与一些公差进行比较。

这是在 nUnit 中检查它的方式:

Assert.That(turnOver, Is.EqualTo(turnoverExpected).Within(0.00001).Percent);

我试图在 xUnit 中做同样的事情,但这就是我想出的全部:

double tolerance = 0.00001;
Assert.Equal(turnOver, turnoverExpected, tolerance);

这不会编译,因为Assert.Equal不采用 type 的第三个参数double

任何人都知道在 xUnit 中执行此操作的好方法吗?

标签: c#xunitassertion

解决方案


您可能稍微误解了Assert.Equal(expected, actual, precision)方法中的最后一个参数(精度)。

 /// <param name="precision">The number of decimal places (valid values: 0-15)</param>

因此,例如,如果您想比较0.00021并且您只想比较0.000224 位小数,您可以这样做(它将返回true):

Assert.Equal(0.00021, 0.00022, 4); // true

这将返回false

Assert.Equal(0.00021, 0.00022, 5); // false

推荐阅读