Nunit как установить visual studio
The NUnit Test Adapter allows you to run NUnit tests inside Visual Studio. The current release, version 2-0, is designed to work with Studio 2012 (All updates), Visual Studio 2013 (All updates) and Visual Studio 2015 (tested with all pre-releases, checked April 2015). Some features are not available under VS2012 RTM.
Note that Releases of Visual Studio prior to VS 2012 did not have the ability to directly run tests built with Open Source testing frameworks like NUnit.
Installation
Beginning with version 0.95 there are two ways of installing the adapter within Visual Studio. See Note 1 below for info on how to choose.
- Use the Extension Manager
- Add it as a Nuget package to your solution. (New in 0.95, requires VS 2012 Update 1 or higher)
Installing With the Extension Manager
To install the NUnit Test Adapter using the Extension Manager, follow these steps:
- From within Visual Studio 2012, 2013 or 2015, select Tools | Extension Manager.
- In the left panel of the Extension Manager, select Online Extensions.
- Locate (search for) the NUnit Test Adapter in the center panel and highlight it.
- Click 'Download' and follow the instructions.
Use the Extension Manager to ensure that the NUnit Test Adapter is enabled.
Installing the Nuget Package
To add it is a Nuget package, you must have an active solution, then follow these steps:
- From Tools menu, use Library Package Manager, select Manage NuGet packages for solution
- In the left panel, select Online
- Locate (search for) NUnit Test Adapter in the center panel and highlight it
- You will find two packages, one without framework and one with framework. See note 2 below for which to choose.
- Click 'Install'
- In the "Select Projects" dialog, you need to select at least one project to add the adapter to, see notes below.
Notes
Note 1: How to choose between Extension and NuGet package
The Extension will apply to Visual Studio itself, and will work for all projects you use. All users of your solution need to install the Extension. If you use TFS Build you must also install the extension to the build system there. The Package will apply to the solution, and will work for any other user too, as it follows the solution, but requires the user to have Update 1 or above. It will also work for any TFS2012 Update 1 or above server build, including TF Service and requires no further installation.
Note 2: Choosing NuGet package
The adapter packages come with and without the NUnit framework. If you have only one test project you can choose the one with framework, that saves you from having to install both the NUnit package and the Adapter package. If you have multiple test projects you need to install the NUnit framework for all of these, but only one of these need the adapter, then choose the adapter package without framework. Installing the adapter for multiple projects will do no harm.
Note 3: Choosing both This will work, but the Nuget package will be ignored. Since this can be confusing, we don't advise it.
Usage
In preparation for using the test adapter, make sure that the Unit Test Explorer is shown in your window. If you don't see it, use the menu ( Test | Windows | Test Explorer ) to show it and position the window where you would like it within Visual Studio.
When you initially open a solution, no tests will be displayed. After compiling the assemblies in the solution, Visual Studio will interact with the NUnit Test Adapter to discover tests and a list of them will be shown in the Test Explorer.
Click on Run All in the Test Explorer to run all the tests. You may also select one or more tests in the list and run them by right-clicking and using the context menu. The context menu also contains entries for debugging tests and for navigating to the source code of a test.
Tests may be grouped by Duration and Outcome under VS2012 RTM and also by Traits and Project using Update 1, and Class using Update 2. NUnit translates any Categories and Properties used on your tests to Visual Studio as Traits.
Tests may be filtered in Visual Studio under Update 1 by Trait, Project, Error Message, File Path, Fully Qualified Name, Output and Outcome. Use the search edit box at the top of the list of tests to specify a filter.
Tests may be organized by play lists in Visual Studio under Update 2. Playlists are more or less equal to the old test lists from VS 2010.
Parameterized tests will show up as separate test cases for each set of parameters.
Known Problems
- There is no test status in Visual Studio corresponding to NUnit's Inconclusive result, so tests with this result are reported as Not Run. Click on the individual test to see the result.
- Theories are reported as individual cases, rather as a single unit.
- Startup performance is substantially improved but is still slower than using NUnit directly.
- A VSIX adapter of older version will be used regardless of version of NuGet adapter.
Workaround: Make sure you have upgraded VSIX adapter to latest version, or uninstalled it if you have the NuGet adapter in a solution. The 0.95 and later versions will output their version number in the Output window under Tests, any older versions will not display a version number.
Issues with other tools
- Versions of Resharper earlier than the 8.2 version has an issue with the NuGet adapter, which will prevent NUnit tests from running. Make sure you have updated Reshaper to at version 8.2.
Further information
For more information see the blogs by Charlie Poole and Terje Sandstrom Also see the following MSDN ALM blog post:
Этот учебник описывает пошаговую процедуру по созданию примера решения для изучения концепций модульного тестирования. Если при изучении учебника вы предпочитаете использовать готовое решение, просмотрите или скачайте пример кода перед началом работы. Инструкции по загрузке см. в разделе Просмотр и скачивание примеров.
Предварительные требования
-
или более поздней версии.
- Текстовый редактор или редактор кода по вашему выбору.
Создание исходного проекта
Откройте окно оболочки. Создайте каталог с именем unit-testing-using-nunit для хранения решения. В этом каталоге выполните следующую команду, чтобы создать файл решения для библиотеки классов и тестового проекта:
Затем создайте каталог PrimeService. Ниже приведена актуальная структура каталогов и файлов:
Перейдите в каталог PrimeService и выполните следующую команду, чтобы создать исходный проект:
Переименуйте Class1.cs в PrimeService.cs. Создайте сбойную реализацию класса PrimeService :
Вернитесь в каталог unit-testing-using-nunit. Чтобы добавить проект библиотеки классов в решение, выполните следующую команду:
Создание тестового проекта
Затем создайте каталог PrimeService.Tests. Ниже представлена структура каталогов:
Перейдите в каталог PrimeService.Tests и создайте проект, выполнив следующую команду:
Команда dotnet new создает тестовый проект, который использует NUnit в качестве библиотеки тестов. Созданный шаблон настраивает средство запуска тестов в файле PrimeServiceTests.csproj:
Тестовый проект требует других пакетов для создания и выполнения модульных тестов. Команда dotnet new на предыдущем шаге добавляет пакет SDK тестирования от Майкрософт, платформу тестирования NUnit и адаптер тестирования NUnit. Теперь добавьте в проект библиотеку классов PrimeService в качестве еще одной зависимости. Использование команды dotnet add reference :
Все содержимое файла можно просмотреть в репозитории образцов на сайте GitHub.
Ниже показан окончательный макет решения:
Выполните следующую команду в каталоге unit-testing-using-nunit:
Создание первого теста
Напишите один тест сбоя теста, запустите его, а затем повторите этот процесс. В каталоге PrimeService.Tests переименуйте файл UnitTest1.cs в PrimeService_IsPrimeShould.cs и замените его содержимое следующим кодом:
Атрибут [TestFixture] обозначает класс, содержащий модульные тесты. Атрибут [Test] указывает, что метод — это метода теста.
Сохраните этот файл и выполните dotnet test , чтобы создать тесты и библиотеку классов, а затем запустите тесты. Средство запуска тестов NUnit содержит точку входа в программу для выполнения тестов. dotnet test запускает средство выполнения тестов с помощью проекта модульного теста, который вы создали.
Тест не будет пройден. Вы еще не создали реализацию. Чтобы тест был пройден, напишите простейший код в классе PrimeService , который работает:
Выполните команду еще раз в каталоге unit-testing-using-nunit. Команда dotnet test запускает сборку для проекта PrimeService и затем для проекта PrimeService.Tests . После сборки обоих проектов она запускает этот отдельный тест. Он выполняется.
Добавление дополнительных возможностей
Теперь, когда тест проходит успешно, пора создать дополнительные тесты. Есть еще ряд элементарных случаев с простыми числами: 0, -1. Можно добавить новые тесты с помощью атрибута [Test] , но это скоро станет утомительным. Есть другие атрибуты NUnit, которые позволяют создавать наборы похожих тестов. Атрибут [TestCase] используется для создания набора тестов, которые выполняют один и тот же код, но имеют разные входные аргументы. С помощью атрибута [TestCase] можно указать значения для этих входных аргументов.
Вместо того чтобы создавать новые тесты, используйте этот атрибут, чтобы создать единый управляемый данными тест, который проверяет несколько значений меньше 2, то есть наименьшего простого числа.
Выполните команду dotnet test , и два из этих тестов завершаются ошибкой. Для успешного выполнения всех тестов нужно изменить предложение if в начале метода Main в файле if :
Продолжайте итерации, добавляя тесты, алгоритмы и код в главной библиотеке. В результате вы получите готовую версию тестов и полную реализацию библиотеки.
Вы создали небольшую библиотеку и набор модульных тестов для нее. Вы структурировали решение, чтобы сделать добавление новых пакетов и тестов частью обычного рабочего процесса и получить возможность сосредоточиться на задачах приложения.
Используйте Visual Studio, чтобы определить и запустить модульные тесты для обеспечения работоспособности кода, нужного объема протестированного кода, а также для обнаружения ошибок и сбоев, прежде чем с ними столкнутся клиенты. Выполняйте модульные тесты регулярно, чтобы обеспечить правильную работу вашего кода.
Создание модульных тестов.
В этом разделе описывается создание проекта модульного теста.
Откройте проект, который хотите протестировать в Visual Studio.
Выберите узел решения в обозревателе решений. Затем в верхней строке меню выберите Файл > Добавить > Новый проект.
В диалоговом окне нового проекта найдите проект модульного теста, который хотите использовать.
Разверните узел Установлено, выберите язык, который вы хотите использовать для своего тестового проекта, после чего выберите Тест.
Нажмите Далее, выберите имя для тестового проекта и нажмите Создать.
Нажмите Далее, выберите имя для тестового проекта и нажмите Создать.
Выберите имя для тестового проекта, например HelloWorldTests, и нажмите OK.
Проект добавляется в решение.
В проекте модульного тестирования добавьте ссылку на проект, который вы хотите протестировать, щелкнув правой кнопкой мыши Ссылки или Зависимости, после чего выбрав Добавить ссылку или Добавить ссылку на проект.
Выберите проект, содержащий код, который будет тестироваться, и нажмите OK.
Добавьте код в метод модульных тестов.
Запуск модульных тестов
Откройте обозреватель тестов, выбрав Тест > Обозреватель тестов в верхней строке меню (или нажмите клавиши CTRL + E, T).
Откройте Обозреватель тестов, выбрав Тест > Windows > Обозреватель тестов в верхней строке меню.
Запустите модульные тесты, нажав Запустить все (или нажмите клавиши CTRL + R, V).
После завершения зеленый флажок указывает, что тест пройден. Красный значок "x" указывает на сбой теста.
Используйте обозреватель тестов для запуска модульных тестов из встроенной платформы тестирования (MSTest) или сторонней платформы тестирования. Вы можете группировать тесты по категориям, фильтровать список тестов, а также создавать, сохранять и запускать списки воспроизведения тестов. Кроме того, с его помощью можно выполнять отладку тестов и анализировать производительность тестов и покрытие кода.
Просмотр результатов динамического модульного тестирования (Visual Studio Enterprise)
Если вы используете платформу тестирования MSTest, xUnit или NUnit в Visual Studio 2017 или более поздней версии, можно просмотреть динамические результаты модульных тестов.
Включите Live Unit Testing в меню Тест, выбрав Тест > Live Unit Testing > Запустить.
Вы можете просматривать результаты тестов в окне редактора кода по мере написания и редактирования кода.
Щелкните индикатор результатов теста для просмотра дополнительных сведений, таких как имена тестов для этого метода.
Дополнительные сведения о Live Unit Testing см. в разделе Live Unit Testing.
Использование сторонней платформы тестирования
Вы можете запускать модульные тесты в Visual Studio с помощью сторонних тестовых платформ, таких как NUnit, Boost или Google C++ Testing Framework, в зависимости от вашего языка программирования. Чтобы использовать стороннюю платформу тестирования, выполните следующие действия.
Используйте диспетчер пакетов NuGet, чтобы установить пакет NuGet для выбранной платформы.
(C++) В Visual Studio 2017 и более поздних версиях уже включены некоторые платформы, такие как Google C++ Testing Framework. Дополнительные сведения см. в статье Написание модульных тестов для C/C++ в Visual Studio.
Добавление проекта модульного тестирования:
Откройте решение, содержащее код, который нужно протестировать.
В обозревателе решений щелкните решение правой кнопкой мыши и выберите Добавить > Создать проект.
Выберите шаблон проекта модульного теста.
Для того примера — NUnit
Щелкните Далее, назовите проект и нажмите кнопку Создать.
Задайте проекту имя и нажмите ОК, чтобы создать его.
Шаблон проекта содержит ссылки на пакеты NuGet для NUnit и NUnit3TestAdapter.
Добавьте ссылку из проекта тестирования на проект, содержащий код, который вы хотите протестировать.
В обозревателе решений щелкните проект правой кнопкой мыши и выберите Добавить > Ссылка. (Ссылку также можно добавить из контекстного меню узла Ссылки или Зависимости.)
Добавьте код в метод теста.
Запустите тест в обозревателе тестов или щелкните правой кнопкой мыши в коде теста и выберите Запустить тесты (или нажмите клавиши CTRL + R, T).
To get a copy of the NUnit 3, you can use various installation approaches.
- Full NUnit install via NuGet.
- NUnitLite install via NuGet.
- Zip and/or MSI file download.
- Combined Approach
Using NuGet Packages
In Visual Studio, from the Tools menu, select NuGet Package Manager | Manage NuGet packages for solution. Open the Browser tab, and Scroll or use search to locate the NUnit and NUnit.Console packages.
NUnit and NUnit.Console
Install both packages. The NUnit package should be referenced by each of your test assemblies, but not by any others.
Locate nunit3-console in the packages\NUnit.ConsoleRunner.3.X.X\tools (or your configured package directory of choice) directory under your solution. This is the location from which you must run nunit3-console when if you would like to run NUnit3 from console. We recommend you only use this approach when running under the control of a script on your build server.
NUnit3TestAdapter
If you want to run NUnit tests automated on a clean machine without any installations (e.g. TFS build agent) - and you're using Visual Studio 2012 or later, use this package.
It's based on the Visual Studio Test Adapter and provides a compiled NUnit3 Visual Studio Test Adapter.
Using NuGet NUnitLite Package
The NUnitLite approach provides a way to run NUnit tests without a full install of the NUnit runner and test engine assemblies. Only the framework and a small runner program are installed. Note that this is currently the only way to run tests under SilverLight 5.0 or the compact framework.
In Visual Studio, from the Tools menu, select NuGet Package Manager | Manage NuGet packages for solution.
Scroll or use search to locate the NUnitLite Version 3 and install it. The package should be referenced by each of your test assemblies, but not by any others.
As a result of your installation, a file named "Program.cs" will have been copied into each of your test projects. NUnitLite test projects are console applications and this file contains the Main() program for your tests. If you already have a Main() in some other class, you may delete the file. This file also contains comments describing how the main should call the NUnitLite runner.
To run your tests, simply run your executable test assembly. No other runner is needed.
Downloading the Zip File
Download the latest binary zip of the NUnit Framework from our Download page. Unzip the file into any convenient directory.
You can also download the latest binary zip or an MSI installer of the NUnit Console from GitHub. Unzip the file or install the MSI and then if you would like be able to run nunit3-console from the command line, put the bin directory, containing nunit3-console.exe on your path.
Run nunit3-console from the command line, giving it the path to your test assembly. To run NUnit's own framework tests from within the NUnit bin directory, enter:
Combined Approach
This approach is useful if you would like to use a single copy of nunit3-console with individual copies of the framework in each project.
Simply follow the zip file procedure to get a central copy of NUnit on your system. Then install the NUnit Version 3 NuGet package in each of your test assemblies. For desktop use by developers, this approach may give you the best of both worlds.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium NUnit Tutorial.
TABLE OF CONTENT
Setting up Visual Studio For NUnit Test Case Development
Before we look at the NUnit setup example, we need to setup the development environment (or IDE) for NUnit test case development. You need to follow the below steps for installing Visual Studio 2019 (VS 2019):
-
Download the latest version of Visual Studio. Depending on the requirement, you can download the Community, Professional, or Enterprise edition of Visual Studio 2019. In this NUnit testing tutorial, we make use of the Community Edition of VS 2019.
The next step is to install the NUnit framework along with setting up the NUnit Visual Studio Adapter.
Installing The Test Runner (NUnit Visual Studio Adapter)
1. NuGet Package
For installing the required NUnit packages, you can either use the IDE or use the NuGet Package Manager commands. If you are just getting started with NUnit, we would recommend that you use the IDE option.
1.1 Using Visual Studio IDE
To install the NUnit framework and NUnit Test Adapter, perform the following steps using the Visual Studio IDE:
1.2 Using Package Manager (PM) Commands
Instead of using the IDE, you can use the Package Manager (PM) commands for installing the required NUnit packages.
-
For executing commands from the PM console, navigate to the Tools -> NuGet Package Manager -> Package Manager Console.
Читайте также: