NUnit checks all array values โ€‹โ€‹(with tolerance)

In NUnit, I can do the following:

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

I can also do this:

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

Now I would like to do something on this line

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

With the exception of the Within keyword, this is not supported. Is there a workaround or other approach that would make this easy?

+8
c # nunit
source share
4 answers

You can set a valid default for floating points:

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

You can do:

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

However, the semantics of Is.EqualTo is slightly different from Is.EquivalentTo - EquivalentTo ignores the order ( {1, 2, 3} equivalent, but not equal to {2, 1, 3} ). If you want to preserve this semantics, the simplest solution is to sort the arrays before approval. If you intend to use this construct, I would suggest writing your own constraint.

+5
source share

Of course, you can use EqualTo to check the values โ€‹โ€‹of the array. Like this:

  /// <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 
+1
source share

Are you trying to use CollectionAssert ? There are many methods to compare.

0
source share

All Articles