How to: Create and Run a Unit Test
Unit tests give developers and testers a quick way to check for logic errors in the methods of classes in C#, Visual Basic .NET, and C++ projects. A unit test can be created one time and run every time that source code is changed to make sure that no bugs are introduced.
This topic covers how to use Microsoft Visual Studio 2010 unit testing tools to automatically generate the skeleton for a unit test from existing code, add validation to fill in that skeleton, create a test category, create a test list, run a test, and read code coverage results.
For a description of the parts of a unit test see Anatomy of a Unit Test.
This example is based on the topic Walkthrough: Creating and Running Unit Tests.
The following figure shows the Create Unit Tests dialog box. It appears when you right-click in a code file that contains methods and then click Create Unit Tests. Unit tests are generated for all the methods that you select in the Types list of the dialog box.
After you have generated your unit tests, a code file is created and changes are shown in your solution explorer.
A separate unit test is created for each method that you select in the Create Unit Test dialog box. In this example, we generated unit tests for the Credit and Debit methods.
Each unit tests that is generated has empty variables and a placeholder Assert statement. The default placeholder Assert statement is usually the Assert.Inconclusive statement.
To make the test meaningful, you have to initialize the variables and replace the placeholder with an appropriate Assert statement. In this example we left the Credit unit test as it was generated, but we initialized the variables and replaced the Assert statement in the Debit test method.
When you first generate unit tests, a test project is created in your solution.
For each class that you are testing, a separate unit test file is created in the test project. In this example, both of the methods we are testing belong to the same class. Therefore, there is only one unit test file, BankAccountTest.cs.
After you run your tests, the results appear in the Test Results window.
There are two phases to creating a unit test.
The first phase is generating a unit test file that contains a skeleton version of a test method for each method in the code that you are testing. Each skeleton test method is generated with empty variables and a placeholder Assert statement.
The second phase is initializing the variables and replacing the placeholder Assert statement with an appropriate one.
Generate the skeletons for your unit tests
You use the Create Unit Tests dialog box to generate unit tests for any or all the methods in the code that you are testing.
Although, typically, methods marked with attributes such as private, internal, and friend are not visible from outside the class of those methods, the Microsoft Visual Studio 2010 tools allow the unit tests access to those methods. For more information about how this works see Unit Tests for Private, Internal, and Friend Methods.
To generate the skeleton for your unit test
Open the code that you want to test in the Visual Studio Code Editor window.
(For ASP.NET services only) If you are testing an ASP.NET Web service, make sure that the project contains an .aspx page. If you create a unit test for a Web service in a project that does not contain an .aspx page, you will receive an error when you try to run the test. For more information, see Unit Tests for ASP.NET Web Services.
Right-click the namespace, class, or method that you want to test, and then click Create Unit Tests.
In the Create Unit Tests dialog box, select the check boxes for all the methods that you want to add to the unit test file.
(Optional) Click Settings to change the default settings for the unit tests that you are creating. These are Visual Studio settings and apply to any unit tests that you create until you change the settings again.
Naming settings: These options let you customize how your test files, test classes, and test methods are named when you generate unit tests.
Mark all test results Inconclusive by default: Select the check box to provide each test method with an Assert.Inconclusive() statement as a placeholder Assert. Clear the check box to eliminate placeholder Asserts.
Enable documentation comments: Select the check box to provide each test method with placeholder comments. Clear the check box to eliminate placeholder comments.
Honor InternalsVisibleTo Attribute: Select the check box to enable methods that are marked as Friend or Internal to be treated as if they were public methods (recommended). Clear the check box to have them tested using a private accessor. For more information about private accessors see Unit Tests for Private, Internal, and Friend Methods.
(Optional) To add tests for methods in assemblies for which you do not have the source code, click Add Assembly. For more information, see How to: Create a Unit Test without Source Code.
In the Output project box, do one of the following:
To create a new test project, select a language for the new project, and then click OK. The New Test Project dialog box appears. You can name the project or accept the default name and then click Create.
To append the methods that are selected in the Create Unit Tests dialog box to the unit test files in an existing test project, select the project in the drop-down list, and then click OK.
Each test method in a unit test file is generated with empty variables and a placeholder Assert statement. You can run such a test, but because there is no real data, you cannot see whether the method behaves as expected. To make the test meaningful, you have to initialize the variables and replace the placeholder Assert statement with one that is appropriate for that method, which is frequently the Assert.AreEqual statement.
To add validation to your unit test
Open the unit test file and locate the unit test for which you want initialize variables.
Locate the variable assignments in the unit test.
In newly generated tests, variable assignments are marked by "TODO" statements that remind you to customize the assignments. For example, the following is a typical assignment that has to be edited:
string target.owner = null; // TODO: Initialize to an appropriate value
Assign an appropriate value to each variable. For an example of assigning appropriate variables, see the procedure "Run and Edit a Unit Test" in Walkthrough: Creating and Running Unit Tests.
You can run your unit tests using a series of different values by creating a data-driven unit test. A data-driven unit test is a unit test that is run repeatedly for each row in a data source. For more information, see How to: Create a Data-Driven Unit Test.
Locate and edit the Assert statement in the unit test. For more information about available Assert statements, see Using the Assert Classes.
(Optional) Add setup and cleanup code for your unit tests by using the [TestInitialize()] and [TestCleanup()] methods of the Microsoft.VisualStudio.TestTools.UnitTesting namespace. When you generate a unit test, an "Additional test attributes" section is added to your unit test file. Expand this section to show commented out methods that can be used to include initialization and cleanup.
You can manage your automated tests by categorizing them using test categories. For more information, see Defining Test Categories to Group Your Tests.
Test categories are recommended over test lists. Test categories allow you to run groups of tests based on their assigned categories without the need to maintain test lists.
To create a new test category
Open the Test View window.
Select a test.
In the properties pane, click Test Categories and then click the ellipses (…) in the right-most column.
In the Test Category window, in the Add New Category box, type a name for your new test category.
Click Add and then click OK.
The new test category will be assigned to your test and it will be available to the other tests through their properties.
Test Lists are a way to collect unit tests into logical groups. The main advantages to adding unit tests to a test list is that you can run tests from multiple unit test files, you can run them as part of a build, and you can use the lists to enforce a check-in policy. For more information about Test Lists, see Defining Test Lists to Group Your Tests.
Test categories are recommended over test list. Test categories allow you to run groups of test based on their assigned categories without the need to maintain test lists.
To create a test list
On the Test menu, click Create New Test List.
In the Create New Test List dialog box, type a name for the list, add a description, select where you want the test list to reside, and then click OK.
To display the available tests, in the Test List Editor window, click All Loaded Tests.
Drag each unit test that you want to add from the main window onto your test list.
Run a unit test
After your unit tests are created, you can run them at any time. This procedure provides one way to run unit tests, but for more information about alternative methods, such as using keyboard shortcuts or the command line, and see How to: Run Automated Tests from Microsoft Visual Studio.
To run a unit test
On the Test menu, point to Windows, and then click Test View.
(Optional) If you want to collect code coverage information, do the following:
On the Test menu, point to Edit Test Settings, and then click the test settings for your current test run.
In the Test Settings dialog box, click Data and Diagnostics.
Under Role select the role you want to use to run your tests.
Check Code Coverage and then click Configure.
Select the check box or boxes to select items for which to collect code coverage information.
In the Code Coverage Detail dialog box, click OK.
In the Test Settings dialog box click Apply and then click Close.
In the Test View window, select one or more tests. To select multiple tests, hold the CTRL key while you click tests.
Click the Run Selection button on the Test View window toolbar. The tests run and the Test Results window opens.
(Optional) To see details about a test, right-click the test in the Test Results window, and then click View Test Results Details.
(Optional) To locate the area of your unit test file that contains an error, in the details window, under Error Stack Trace, click the error's link.
For more information about understanding your test results, see Reviewing Test Results.
If you chose to collect code coverage information, you can open the Code Coverage window to see what percentage of the methods in the code that you are testing were covered by your unit tests. For more information about how to check the code coverage of tests that have already been run, and for more information about how to manage the code coverage results, see Code Coverage Data Overview.
To view code coverage for unit tests
In the Test Results window, on the toolbar, click Show Code Coverage Results. You may have to enlarge the window to see the button.
The Code Coverage Results window opens.
This window shows the extent to which method was tested.