xUnit 断言两个值相等且具有一定的容差

我正在尝试比较两个数字的精度和一定的容差。

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

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

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

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

这不会编译,因为Assert.Equal不接受类型为 的第三个参数double

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


吃鸡游戏
浏览 166回答 4
4回答

森栏

您可能稍微误解了方法中的最后一个参数(精度)Assert.Equal(expected, actual, precision)。&nbsp;///&nbsp;<param&nbsp;name="precision">The&nbsp;number&nbsp;of&nbsp;decimal&nbsp;places&nbsp;(valid&nbsp;values:&nbsp;0-15)</param>因此,举例来说,如果您想要比较0.00021并且0.00022您只想比较小数点后 4 位,您可以这样做(它将返回true):Assert.Equal(0.00021,&nbsp;0.00022,&nbsp;4);&nbsp;//&nbsp;true这将返回false:Assert.Equal(0.00021,&nbsp;0.00022,&nbsp;5);&nbsp;//&nbsp;false

倚天杖

您可以使用FluentAssertionsfloat value = 3.1415927F; value.Should().BeApproximately(3.14F, 0.01F);

蝴蝶刀刀

您可以Assert.InRange()在签名所在的位置使用 ,public&nbsp;static&nbsp;void&nbsp;InRange<T>(T&nbsp;actual,&nbsp;T&nbsp;low,&nbsp;T&nbsp;high)&nbsp;where&nbsp;T&nbsp;:&nbsp;IComparable

桃花长相依

我将一些测试从 MS Test V1 移植到 xUnit,并注意到Assert带有 Delta 的测试与 xUnit 中的测试不同。为了解决这个问题,我反编译了 MS Test 中的版本并制作了我自己的版本:internal static class DoubleAssertion{&nbsp; &nbsp; const Double delta = 0.00001;&nbsp; &nbsp; public static void Equal(Double expected, Double actual, String message = null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (Math.Abs(expected - actual) > delta)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var deltaMessage = $"Expected a difference no greater than <{delta.ToString(CultureInfo.CurrentCulture.NumberFormat)}>";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!String.IsNullOrWhiteSpace(message))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message = message + Environment.NewLine + deltaMessage;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message = deltaMessage;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new DoubleException(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expected: expected.ToString(CultureInfo.CurrentCulture.NumberFormat),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; actual: actual.ToString(CultureInfo.CurrentCulture.NumberFormat),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message: message);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public class DoubleException : AssertActualExpectedException{&nbsp; &nbsp; public DoubleException(&nbsp; &nbsp; &nbsp; &nbsp; String expected,&nbsp; &nbsp; &nbsp; &nbsp; String actual,&nbsp; &nbsp; &nbsp; &nbsp; String message)&nbsp; &nbsp; &nbsp; &nbsp; : base(expected, actual, message)&nbsp; &nbsp; {&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP