NUnit tolerance on double arrays

Yesterday I wanted to compare two arrays of doubles in a unit test to make sure I didn’t change some resulting calculations when refactoring.

var expected = new double[] { 1.00000000000000006 , 2.00000000000000005 ,
3.00000000000000008 , 4.00000000000000007 , 5.0000000000000005 };
Assert.AreEqual(expected, process.GetResults());

It turns out that when I printed my expected results to get these constants, my print statement rounded them down to the displayed 15 decimal places. Rather than go print a longer constant to be used in my test, I wanted the ability to test within a given threshold.

It wasn’t until today that I decided to dive into NUnit and implement the needed methods when I browsed the NUnit source and discovered that this functionality already exists. The key is using the correct method overload. the above ends up with no overload. Indeed any arrays passed end up calling to Assert.AreEqual(object,object…) style overloads.

The answer is simple: use NUnit’s Constraint Model assertions.


Assert.That(expected, Is.EqualTo(process.GetResults()).Within(0.0000000001));

Works great! Thank NUnit!