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 )]
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With