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

Ben*_*ttr 12 c# nunit

在NUnit中,我可以执行以下操作:

Assert.That(1.05,Is.EqualTo(1.0).Within(0.1));
Run Code Online (Sandbox Code Playgroud)

我也能做到这一点:

Assert.That(new[]{1.0,2.0,3.0},Is.EquivalentTo(new[]{3.0,2.0,1.0}));
Run Code Online (Sandbox Code Playgroud)

现在我想沿着这条线做点什么

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

除了Within在这种情况下不支持关键字.是否有解决方法或其他方法可以轻松地做到这一点?

小智 12

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

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


mac*_*kow 8

你可以做:

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

但是,Is.EqualTo语义与Is.EquivalentTo- EquivalentTo忽略顺序({1, 2, 3}等同,但不等于{2, 1, 3})略有不同.如果您想保留这种语义,最简单的解决方案是在断言之前对数组进行排序.如果你要使用这个构造很多,我会建议为此编写自己的约束.