Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

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

Figure 270 You are prompted to name the test project Use the default - фото 74

Figure 2-70

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

Figure 271 The TestProject1is be added to Solution Explorer see Figure 272 - фото 75

Figure 2-71

The TestProject1is be added to Solution Explorer (see Figure 2-72).

Figure 272 The content of the PointTestcsclass is now displayed in Visual - фото 76

Figure 2-72

The content of the PointTest.csclass is now displayed in Visual Studio 2008. This class contains the various methods that you can use to test the Pointclass. In particular, note the lengthTest()method:

/// < summary>

///A test for length

///

[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 Pointobjects and then call the length()method of the Pointclass to calculate the distance between the two points:

///



///A test for length

///

[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 Assertclass 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 273 To run the unit test click the Run All Tests in Solution button in - фото 77

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 274 You can make modifications to the lengthTest method to test other - фото 78

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 275 Testing with Floating Point Numbers You need to take special note - фото 79

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() {

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 276 Why is this so The reason is that floating point numbers such as - фото 80

Figure 2-76

Why is this so? The reason is that floating point numbers (such as Singleand 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.

Adding Additional Test Methods

You can insert additional test methods by adding new subroutines to the PointTest.csfile and prefixing them with the [TestMethod]attribute. For example, the following test method uses the AreSame()method of the Assertclass to check whether two objects are pointing to the same reference:

[TestMethod()]

public void objectTest() {

Point point1 = new Point(4, 5);

Point point2 = new Point() { x = 4, y = 5 };

Point point3 = point2;

//---Failed---

Assert.AreSame(point1, point2, "point1 is not the same as point2";

//---Passed---

Assert.AreSame(point2, point3, "point2 is not the same as point3";

}

Figure 2-77 shows the test results.

Figure 277 Summary This chapter provided a quick overview of the common - фото 81

Figure 2-77

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x