4

I have an algorithm that converts a value between celsius and farhrenheit. To test that it works with a wide range of values I'm using NUnit's TestCases like so:

[TestCase( 0, Result = -17.778 )]
[TestCase( 50, Result = 10 )]
public double FahrenheitToCelsius(double val) {
    return (val - 32) / 1.8;
}

The problem is that the first TestCase fails because it tests for an exact match.
One solution that I have found is to do something like this:

[TestCase( 0, -17.778 )]
[TestCase( 50, 10 )]
public void FahrenheitToCelsius2(double val, double expected) {
    double result =  (val - 32) / 1.8;
    Assert.AreEqual( expected, result, 0.005 );
}

But I'm not too happy with it. My question is:
Can a tolerance for the result be defined in the TestCase?

Update:
To clarify, I'm looking for something along the lines of:

[TestCase( 0, Result = 1.1, Tolerance = 0.05 )]
Fabi1816
  • 389
  • 1
  • 4
  • 16
  • 1
    Why don't you just.. add another parameter to your `[TestCase()]`? – Jeroen Vannevel Nov 12 '14 at 15:43
  • 1
    This is exactly what the Within() constraint is for, so as @Jeroen says just add a third parameter to the test case. Perhaps use a fourth one to specify Ulps (Units in the Last Place) if you want greater control. See http://www.nunit.org/index.php?p=equalConstraint&r=2.5.5 – ClickRick Nov 12 '14 at 15:50

2 Answers2

10

NUnit also provides the DefaultFloatingPointTolerance attribute.

You can use it to set the default tolerance, either on a method or on a class level.

[TestCase( 0, Result = -17.778 )]
[TestCase( 50, Result = 10 )]
[DefaultFloatingPointTolerance(0.05)]
public double FahrenheitToCelsius(double val) {
    return (val - 32) / 1.8;
}

This approach keeps your code minimal as you don't have to add the expected method parameter.

Reference: https://docs.nunit.org/articles/nunit/writing-tests/attributes/defaultfloatingpointtolerance.html

Francois Botha
  • 4,520
  • 1
  • 34
  • 46
5

Add another parameter to the test case:

[TestCase(0, -17.778, .005)]
[TestCase(50, 10, 0)]
public void FahrenheitToCelsius2(double fahrenheit, double expected, double tolerance)
{
    double result = (fahrenheit - 32) / 1.8;
    Assert.AreEqual(expected, result, tolerance);
}
Andrew Radford
  • 3,227
  • 1
  • 20
  • 25