Книга: C# 2008 Programmer
Creating the Test
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 test methods.
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() {
int x = 3;
int y = 4;
Point target = new Point(x, y);
Point pointOne = new Point(0,0);
double expected = 5F;
double actual;
actual = target.length(pointOne);
Assert.AreEqual(expected, actual,
"UnitTesting.Point.length did not return the expected value.");
}
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.