Книга: C# 2008 Programmer
Testing with Floating Point Numbers
Testing with Floating Point Numbers
You need to take special note when your test involves comparing floating point numbers. Consider the following example:
[TestMethod()]
public void lengthTest() {
int x = 4;
int y = 5;
Point target = new Point(x, y);
Point pointOne = new Point(1,2);
double expected = 4.24264F;
double actual;
actual = target.length(pointOne);
Assert.AreEqual(expected, actual,
"UnitTesting.Point.length did not return the expected value.");
}
When you run the test, the test will fail (see Figure 2-76).
Figure 2-76
Why is this so? The reason is that floating point numbers (such as Single
and Double
) are not stored exactly as what they have been assigned. For example, in this case, the value of 4.24264 is stored internally as 4.2426400184631348, and the result returned by the length()
method is actually 4.2426406871192848. The AreEqual()
method actually fails if you compare them directly.
To address this issue, the AreEqual()
method supports a third parameter — delta
— that specifies the maximum difference allowed for the two numbers that you are comparing. In this case, the difference between the two numbers is 0.0000066865615. And so the following code will pass the test:
Assert.AreEqual(expected, actual, 0.0000066865616,
"UnitTesting.Point.length did not return the expected value.");
But this code will fail:
Assert.AreEqual(expected, actual, 0.0000066865615,
"UnitTesting.Point.length did not return the expected value.");
Assert.AreEqual(expected, actual, 0.0000066865614,
"UnitTesting.Point.length did not return the expected value.");
Although the documentation says that the delta specifies the maximum difference allowed for the two numbers, in actual testing the difference should be less than the delta for the Assert.AreEqual()
method to pass. This explains why that first statement fails.
- Unit Testing
- Using Double Quotes to Resolve Variables in Strings with Embedded Spaces
- Drawbacks with restore
- Интеграция Windows SharePoint и Microsoft Office
- 7. AGGREGATION WITH INDEPENDENT WORKS
- Получение помощи по Windows SharePoint Services 3.0
- Службы Windows SharePoint
- Версии служб Windows SharePoint
- Продукты и технологии Microsoft SharePoint
- Переход по узлу SharePoint и домашней странице
- Просмотр списков на узле SharePoint
- Отправка данных в списки SharePoint по электронной почте