Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit checking all the values of an array (with tolerance)

Tags:

c#

nunit

In NUnit I am able to do the following:

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

I am also able to do that:

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 along these line

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

Except the Within keyword is not supported in that situation. Is there a workaround or another approach that would allow to do that easily?

like image 709
Benoittr Avatar asked Jul 15 '11 13:07

Benoittr


2 Answers

You can set the default tolerance 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}));
like image 106
Cooker Avatar answered Oct 20 '22 00:10

Cooker


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, Is.EqualTo semantics is somewhat different from Is.EquivalentTo - EquivalentTo ignores order ( {1, 2, 3} is equivalent, but not equal to {2, 1, 3}). If you'd like to preserve this semantics, the simplest solution is to sort arrays before assertion. If you're going to use this construct a lot I would suggest to write your own constraint for that.

like image 22
maciejkow Avatar answered Oct 20 '22 00:10

maciejkow