Math.Pow(this.y - pointOne.y, 2));
}
}
}
Creating the Test
For this example, create a unit test to test the length()
method. To do so, right-click on the length()
method and select Create Unit Tests (see Figure 2-69).

Figure 2-69
In the Create Unit Tests dialog, select any other additional members you want to test and click OK (see Figure 2-70).

Figure 2-70
You are prompted to name the test project. Use the default TestProject1
and click Create. You may also be prompted with the dialog shown in Figure 2-71. Click Yes.

Figure 2-71
The TestProject1
is be added to Solution Explorer (see Figure 2-72).

Figure 2-72
The content of the PointTest.cs
class is now displayed in Visual Studio 2008. This class contains the various methods that you can use to test the Point
class. In particular, note the lengthTest()
method:
/// < summary>
///A test for length
///</summary>
[TestMethod()]
public void lengthTest() {
Point target = new Point(); // TODO: Initialize to an appropriate value
Point pointOne = null; // TODO: Initialize to an appropriate value
double expected = 0F; // TODO: Initialize to an appropriate value
double actual;
actual = target.length(pointOne);
Assert.AreEqual(expected, actual);
Assert.Inconclusive('Verify the correctness of this test method.');
}
The lengthTest()
method has the [TestMethod]
attribute prefixing it. Methods with that attribute are known as
Now modify the implementation of the lengthTest()
method to basically create and initialize two Point
objects and then call the length()
method of the Point
class to calculate the distance between the two points:
/// <summary>
///A test for length
///</summary>
[TestMethod()]
public void lengthTest() {
double actual;
actual = target.length(pointOne);
}
Once the result is returned from the length()
method, you use the AreEqual()
method from the Assert
class to check the returned value against the expected value. If the expected value does not match the returned result, the error message set in the AreEqual()
method is displayed.
Running the Test
Before you run the unit test, take a look at the Test Tools toolbar (see Figure 2-73) automatically shown in Visual Studio 2008.

Figure 2-73
To run the unit test, click the Run All Tests in Solution button in the toolbar. In this case, the lengthTest()
method passed the test. The length between two points (3,4) and (0,0) is indeed 5 (see Figure 2-74).

Figure 2-74
You can make modifications to the lengthTest() method to test other parameters. In the Test Results window, you have the option to view the previous test results (see Figure 2-75).

Figure 2-75
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() {
Point target = new Point(x, y);
Point pointOne = new Point(1,2);
double actual;
actual = target.length(pointOne);