To address this issue, the
AreEqual() method supports a third parameter:
delta parameter specifies the maximum difference allowed for the two numbers that you are comparing. In this case, the difference between the two numbers in question is 0.00000047683716. And so the following code will pass the test:
<TestMethod()> _ Public Sub lengthTest() Dim x As Integer = 4 Dim y As Integer = 5 Dim target As Point = New Point(x, y) Dim pointOne As Point = New Point(1, 2) Dim expected As Single = 4.24264 Dim actual As Single actual = target.length(pointOne) Assert.AreEqual(expected, actual, 0.00000047683716, _ "UnitTesting.Point.length did not return the expected value.") End Sub
But the following will fail the test (see Figure 8):
Assert.AreEqual(expected, actual, 0.00000047683715, _ "UnitTesting.Point.length did not return the expected value.")
Figure 8. The
lengthTest() method failed the test
The following tests will also pass:
Assert.AreEqual(expected, actual, 0.00000047683716, _ "UnitTesting.Point.length did not return the expected value.") Assert.AreEqual(expected, actual, 0.00000047683717, _ "UnitTesting.Point.length did not return the expected value.")
In general, when comparing floating point numbers, it would be useful to specify a small
delta, such as 0.05, to compensate for the rounding errors inherent in storing floating point numbers.
Adding Additional Test Methods
You can insert additional test methods by adding new subroutines to the PointTest.vb file and prefixing them with the
<TestMethod> attribute. For example, the following test method uses the
AreSame() method of the
Assert class to check whether two objects are the pointing to the same reference:
<TestMethod()> _ Public Sub objectTest() Dim point1 As Point = New Point(4, 5) Dim point2 As New Point point2.x = 4 point2.y = 5 Dim point3 As Point = point2 Assert.AreSame(point1, point2) '--Failed Assert.AreSame(point2, point3) '--Passed End Sub
Figure 9 shows the result of the two test methods in the PointTest.vb file: lengthTest and objectTest.
Figure 9. Viewing the test results
In this article, I have shown you how you can perform unit testing on your application using the Visual Studio 2005 Team System. Let me know if this feature is useful to you via the talkback below.
Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.
Return to the Windows DevCenter.