С unit test windows

Unit test tools and tasks

Unit tests give developers and testers a quick way to look for logic errors in the methods of classes in C#, Visual Basic, and C++ projects.

The unit test tools include:

Test Explorer—Run unit tests and see their results in Test Explorer. You can use any unit test framework, including a third-party framework, that has an adapter for Test Explorer.

Microsoft unit test framework for managed code—The Microsoft unit test framework for managed code is installed with Visual Studio and provides a framework for testing .NET code.

Microsoft unit test framework for C++—The Microsoft unit test framework for C++ is installed as part of the Desktop development with C++ workload. It provides a framework for testing native code. Google Test, Boost.Test, and CTest frameworks are also included, and third-party adapters are available for additional test frameworks. For more information, see Write unit tests for C/C++.

Code coverage tools—You can determine the amount of product code that your unit tests exercise from one command in Test Explorer.

Microsoft Fakes isolation framework—The Microsoft Fakes isolation framework can create substitute classes and methods for production and system .NET code that create dependencies in the code under test. By implementing the fake delegates for a function, you control the behavior and output of the dependency object.

For .NET, you can also use IntelliTest to explore your code and generate test data and a suite of unit tests. For every statement in the code, a test input is generated that will execute that statement. A case analysis is performed for every conditional branch in the code.

Key tasks

Use the following articles to help with understanding and creating unit tests:

Модульное тестирование кода C# Unit test C# code

Эта статья описывает один из способов создания модульных тестов для класса C# в приложении UWP. This article describes one way to create unit tests for a C# class in a UWP app.

Класс Rooter, который является тестируемым, реализует функцию, вычисляющую оценку квадратного корня заданного числа. The Rooter class, which is the class under test, implements a function that calculates an estimate of the square root of a given number.

В этой статье демонстрируется разработка на основе тестов. This article demonstrates test-driven development. При таком подходе сначала необходимо написать тест, который проверяет определенное поведение тестируемой системы, а затем написать код, который проходит этот тест. In this approach, you first write a test that verifies a specific behavior in the system that you’re testing, and then you write the code that passes the test.

Читайте также:  Лагает дота 2 linux

Создание решения и проекта модульного теста Create the solution and the unit test project

В меню Файл последовательно выберите пункты Создать > Проект. On the File menu, choose New > Project.

Найдите и выберите шаблон проекта Пустое приложение (универсальное приложение для Windows). Search for and select the Blank App (Universal Windows) project template.

Задайте для проекта имя Maths. Name the project Maths.

В обозревателе решений щелкните решение правой кнопкой мыши и выберите пункты Добавить > Новый проект. In Solution Explorer, right-click on the solution and choose Add > New Project.

Найдите и выберите шаблон проекта Приложение модульного тестирования (универсальное приложение Windows). Search for and select the Unit Test App (Universal Windows) project template.

Задайте для тестового проекта имя RooterTests. Name the test project RooterTests.

Проверка с помощью обозревателя тестов, что тесты запускаются Verify that the tests run in Test Explorer

Добавьте какой-нибудь тестовый код в TestMethod1 в файле UnitTest.cs: Insert some test code into TestMethod1 in the UnitTest.cs file:

Класс Assert содержит несколько статических методов, которые можно использовать для проверки результатов в тестовых методах. The Assert class provides several static methods that you can use to verify results in test methods.

  1. В меню Тест выберите Выполнить >Все тесты. On the Test menu, choose Run >All Tests.
  1. В меню Тест выберите Выполнить все тесты. On the Test menu, choose Run All Tests.

Будет построен и запущен проект теста. The test project builds and runs. Подождите, так как это может занять некоторое время. Be patient because it may take a little while. Появится окно обозревателя тестов, а тест будет указан в разделе Пройденные тесты. The Test Explorer window appears, and the test is listed under Passed Tests. Область сводки в нижней части окна содержит дополнительные сведения о выбранном тесте. The Summary pane at the bottom of the window provides additional details about the selected test.

Добавьте в проект Maths класс Rooter Add the Rooter class to the Maths project

В обозревателе решений щелкните правой кнопкой мыши проект Maths, а затем выберите Добавить > Класс. In Solution Explorer, right-click on the Maths project, and then choose Add > Class.

Назовите файл класса Rooter.cs. Name the class file Rooter.cs.

Добавьте следующий код в файл Rooter.cs класса Rooter: Add the following code to the Rooter class Rooter.cs file:

Класс Rooter объявляет конструктор и метод оценки SquareRoot. The Rooter class declares a constructor and the SquareRoot estimator method. Метод SquareRoot представляет собой минимальную реализацию, достаточную для проверки базовой структуры тестирования. The SquareRoot method is only a minimal implementation, just enough to test the basic structure of the testing setup.

Добавьте ключевое слово public в объявление класса Rooter, чтобы код теста мог получить к нему доступ. Add the public keyword to the Rooter class declaration, so the test code can access it.

Читайте также:  Oracle virtualbox для windows 64 bit

Добавление ссылки на проект Add a project reference

Добавьте ссылку на приложение Maths в проект RooterTests. Add a reference from the RooterTests project to the Maths app.

В обозревателе решений щелкните правой кнопкой мыши проект RooterTests и выберите Добавить > Ссылка. In Solution Explorer, right-click on the RooterTests project, and then choose Add > Reference.

В диалоговом окне Добавить ссылку — RooterTests разверните узел Решение и выберите Проекты. In the Add Reference — RooterTests dialog box, expand Solution and choose Projects. Выберите проект Maths. Select the Maths project.

Добавьте в файл UnitTest.cs инструкцию using : Add a using statement to the UnitTest.cs file:

Откройте файл UnitTest.cs. Open UnitTest.cs.

Добавьте следующий код ниже строки using Microsoft.VisualStudio.TestTools.UnitTesting; : Add this code below the using Microsoft.VisualStudio.TestTools.UnitTesting; line:

Добавьте тест, использующий функцию Rooter. Add a test that uses the Rooter function. Добавьте в файл UnitTest.cs следующий код: Add the following code to UnitTest.cs:

Новый тест появится в обозревателе тестов в узле Незапускавшиеся тесты. The new test appears in Test Explorer in the Not Run Tests node.

Чтобы избежать ошибки, когда полезная нагрузка содержит два или больше файлов с одним и тем же путем назначения, в обозревателе решений разверните узел Свойства в проекте Maths, а затем удалите файл Default.rd.xml. To avoid a «Payload contains two or more files with the same destination path» error, in Solution Explorer, expand the Properties node under the Maths project, and then delete the Default.rd.xml file.

В обозревателе тестов выберите Запустить все. In Test Explorer, choose Run All.

Выполняется сборка решения, запускаются и успешно выполняются тесты. The solution builds and the tests run and pass.

В разделе обозреватель тестов выберите Выполнить все тесты. In Test Explorer, choose Run All Tests.

Выполняется сборка решения, запускаются и успешно выполняются тесты. The solution builds and the tests run and pass.

Вы настроили проекты тестов и приложений и убедились, что можно выполнять тесты, вызывающие функции в проекте приложения. You’ve set up the test and app projects and verified that you can run tests that call functions in the app project. Теперь можно начать писать реальные тесты и код. Now you can begin to write real tests and code.

Итеративное расширение тестов и обеспечение их успешного выполнения Iteratively augment the tests and make them pass

Добавьте новый тест с именем RangeTest: Add a new test called RangeTest:

Рекомендуется не изменять пройденные тесты. We recommend that you do not change tests that have passed. Вместо этого добавьте новый тест. Add a new test instead.

Запустите тест RangeTest и убедитесь, что он завершается сбоем. Run the RangeTest test and verify that it fails.

Сразу после написания теста запустите его, чтобы убедиться в его сбое. Immediately after you write a test, run it to verify that it fails. Это поможет избежать распространенной ошибки, заключающейся в написании теста, который никогда не завершается сбоем. This helps you avoid the easy mistake of writing a test that never fails.

Читайте также:  Принтер hp 2605 драйвер для windows 10

Измените код теста, чтобы новый тест был пройден. Enhance the code under test so that the new test passes. Измените функцию SquareRoot в файле Rooter.cs следующим образом: Change the SquareRoot function in Rooter.cs to this:

  1. В обозревателе тестов выберите Запустить все. In Test Explorer, choose Run All.
  1. В разделе обозреватель тестов выберите Выполнить все тесты. In Test Explorer, choose Run All Tests.

Теперь все три теста проходятся. All three tests now pass.

Разрабатывайте код, добавляя тесты по одному. Develop code by adding tests one at a time. После каждой итерации проверяйте, все ли тесты завершаются успешно. Make sure that all the tests pass after each iteration.

Рефакторинг кода Refactor the code

В этом разделе вы выполните рефакторинг кода приложения и теста, а затем повторно запустите тесты, чтобы убедиться, что они выполняются успешно. In this section, you refactor both app and test code, then rerun tests to make sure they still pass.

Упрощение оценки квадратного корня Simplify the square root estimation

Упростите централизованное вычисление в функции SquareRoot, изменив одну строку кода следующим образом: Simplify the central calculation in the SquareRoot function by changing one line of code, as follows:

Выполните все тесты, чтобы убедиться, что не введена регрессия. Run all tests to make sure that you haven’t introduced a regression. Все тесты должны успешно выполниться. They should all pass.

Стабильный набор хороших модульных тестов придает уверенность в том, что изменение кода не привело к появлению ошибок. A stable set of good unit tests gives confidence that you have not introduced bugs when you change the code.

Исключение повторяющегося кода Eliminate duplicated code

В методе RangeTest жестко задан знаменатель переменной отклонения, которая используется в методе Assert. The RangeTest method hard codes the denominator of the tolerance variable that’s passed to the Assert method. Если планируется добавлять другие тесты, которые используют такой же расчет отклонения, использование жестко запрограммированных значений в нескольких местах может усложнить работу с кодом. If you plan to add additional tests that use the same tolerance calculation, the use of a hard-coded value in multiple locations makes the code harder to maintain.

Добавьте к классу UnitTest1 закрытый вспомогательный метод для вычисления значения отклонения, а затем вызывайте этот метод из RangeTest. Add a private helper method to the UnitTest1 class to calculate the tolerance value, and then call that method from RangeTest.

Запустите тест RangeTest, чтобы убедиться, что он все еще успешно выполняется. Run RangeTest to make sure that it still passes.

При добавлении вспомогательного метода в тестовый класс, который не должен отображаться в обозревателе тестов, не добавляйте к этому методу атрибут TestMethodAttribute. If you add a helper method to a test class, and you don’t want it to appear in Test Explorer, don’t add the TestMethodAttribute attribute to the method.

Оцените статью