简体   繁体   English

如何向 NUnit 测试用例添加结果容差

[英]How to add a result tolerance to a NUnit TestCase

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:为了测试它是否适用于广泛的值,我正在使用 NUnit 的 TestCases,如下所示:

[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.问题是第一个 TestCase 失败了,因为它测试了完全匹配。
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 )]

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);
}

NUnit also provides the DefaultFloatingPointTolerance attribute. NUnit 还提供DefaultFloatingPointTolerance属性。

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.这种方法使您的代码最少,因为您不必添加expected方法参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM