How can I compare doubles using a specified tolerance in NUnit?

I think what I would have done is simply define a function somewhere in your test harness

public static bool AreEqual( double[], double[], double delta )

that does the comparison and returns true or false appropriately. In your Test you simply write :

Assert.IsTrue( AreEqual( expected, result, delta ) ) ;

"Better" is always a matter of taste. In this case, i would say yes. You should make your own assert, without subclassing the nunit assert. Nunit already has multiple Assert classes with different specific assertions. Like CollectionAssert. Otherwise your method is fine.


I had a need to create custom assert, in your case there was an alternative provided by the framework. However this didn't work when I wanted to have a completely custom assert. I solved this by adding a new static class calling into nunit.

public static class FooAssert
{
     public static void CountEquals(int expected, FooConsumer consumer)
     {
         int actualCount = 0;
         while (consumer.ConsumeItem() != null)
             actualCount++;

         NUnit.Framework.Assert.AreEqual(expected, actualCount);
     }
}

Then in a test

[Test]
public void BarTest()
{
    // Arrange
    ... 

    // Act
    ...

    // Assert
    FooAssert.CountEquals(1, fooConsumer);
}

I know I am a little bit late for the party, it might still be useful for somebody


Since the introduction of the fluent assertion syntax in NUnit, the Within() method has been available for this purpose:

double actualValue = 1.989;
double expectedValue = 1.9890;
Assert.That(actualValue, Is.EqualTo(expectedValue).Within(0.00001));
Assert.That(actualValue, Is.EqualTo(expectedValue).Within(1).Ulps);
Assert.That(actualValue, Is.EqualTo(expectedValue).Within(0.1).Percent);

For collections, the default behaviour of Is.EqualTo() is to compare the collections' members individually, with these individual comparisons being modified by Within(). Hence, you can compare two arrays of doubles like so:

var actualDoubles = new double[] {1.0 / 3.0, 0.7, 9.981};
var expectedDoubles = new double[] { 1.1 / 3.3, 0.7, 9.9810};
Assert.That(actualDoubles, Is.EqualTo(expectedDoubles).Within(0.00001));
Assert.That(actualDoubles, Is.EqualTo(expectedDoubles).Within(1).Ulps);
Assert.That(actualDoubles, Is.EqualTo(expectedDoubles).Within(0.1).Percent);

This will compare each element of actualDoubles to the corresponding element in expectedDoubles using the specified tolerance, and will fail if any are not sufficiently close.

Tags:

C#

Nunit