NUnit检查数组的所有值(带公差)

本文关键字:检查 数组 NUnit | 更新日期: 2023-09-27 18:02:32

在NUnit中,我可以做以下事情:

Assert.That(1.05,Is.EqualTo(1.0).Within(0.1));

我也可以这样做:

Assert.That(new[]{1.0,2.0,3.0},Is.EquivalentTo(new[]{3.0,2.0,1.0}));

现在我想在这一行做点什么

Assert.That(new[]{1.05,2.05,3.05},
   Is.EquivalentTo(new[]{3.0,2.0,1.0}).Within(0.1));

在这种情况下不支持Within关键字。有没有一种变通方法或其他方法可以轻松地做到这一点?

NUnit检查数组的所有值(带公差)

可以设置浮点数的默认容差:

GlobalSettings.DefaultFloatingPointTolerance = 0.1;
Assert.That(new[] {1.05, 2.05, 3.05}, Is.EquivalentTo(new[] {3.0, 2.0, 1.0}));

你可以这样做:

var actual = new[] {1.05, 2.05, 3.05};
var expected = new[] { 1, 2, 3 };
Assert.That(actual, Is.EqualTo(expected).Within(0.1));

然而,Is.EqualTo的语义与Is.EquivalentTo有所不同——EquivalentTo忽略顺序({1, 2, 3}是等价的,但不等于{2, 1, 3})。如果希望保留这种语义,最简单的解决方案是在断言之前对数组进行排序。如果你要经常使用这个结构,我建议你自己编写约束

当然,您可以使用EqualTo来检查数组值。这样的:

  /// <summary>
  /// Validate the array is within a specified amount
  /// </summary>
  [Test]
  public void ValidateArrayWithinValue()
  {
     var array1 = new double[] { 0.0023d, 0.011d, 0.743d };
     var array2 = new double[] { 0.0033d, 0.012d, 0.742d };
     Assert.That(array1, Is.EqualTo(array2).Within(0.00101d), "Array Failed Constaint!");
  } // ValidateArrayWithinValue