How to: Create and Run a Unit Test

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

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 11 Developer Preview 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.

An example 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.

The following figure shows that in this example, unit tests will be generated for the Credit and Debit methods.

Create Unit Tests dialog box

After you have generated your unit tests, a code file is created and changes are shown in your solution explorer.

The following figure shows the results of creating the unit tests.

Title Owner Needed By Art Status

  1. 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.

  2. 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.

  3. 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.

  4. When you first generate unit tests, a test project is created in your solution.

  5. 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.

  6. After you run your tests, the results appear in the Test Results window.

Create a Unit Test

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.

Note

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 11 Developer Preview 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

  1. Open the code that you want to test in the Visual Studio Code Editor window.

  2. (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.

  3. Right-click the namespace, class, or method that you want to test, and then click Create Unit Tests.

  4. 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.

  5. (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.

  6. (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.

  7. 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.

Add validation to your unit tests

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

  1. Open the unit test file and locate the unit test for which you want initialize variables.

  2. 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

  3. 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.

    Note

    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.

  4. Locate and edit the Assert statement in the unit test. For more information about available Assert statements, see Using the Assert Classes.

  5. (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.

(Optional) Create a Test Category

You can manage your automated tests by categorizing them using test categories. For more information, see Defining Test Categories to Group Your Tests.

Note

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

  1. Open the Test View window.

  2. Select a test.

  3. In the properties pane, click Test Categories and then click the ellipses (…) in the right-most column.

  4. In the Test Category window, in the Add New Category box, type a name for your new test category.

  5. 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.

(Optional) Create a Test List

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.

Note

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

  1. On the Test menu, click Create New Test List.

  2. 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.

  3. To display the available tests, in the Test List Editor window, click All Loaded Tests.

  4. 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

  1. On the Test menu, point to Windows, and then click Test View.

  2. (Optional) If you want to collect code coverage information, do the following:

    1. On the Test menu, point to Edit Test Settings, and then click the test settings for your current test run.

    2. In the Test Settings dialog box, click Data and Diagnostics.

    3. Under Role select the role you want to use to run your tests.

    4. Check Code Coverage and then click Configure.

    5. Select the check box or boxes to select items for which to collect code coverage information.

    6. In the Code Coverage Detail dialog box, click OK.

    7. In the Test Settings dialog box click Apply and then click Close.

  3. In the Test View window, select one or more tests. To select multiple tests, hold the CTRL key while you click tests.

  4. Click the Run Selection button on the Test View window toolbar. The tests run and the Test Results window opens.

  5. (Optional) To see details about a test, right-click the test in the Test Results window, and then click View Test Results Details.

  6. (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.

(Optional) View Code Coverage

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

  1. In the Test Results window, on the toolbar, click Show Code Coverage Results. You may have to enlarge the window to see the button.

  2. The Code Coverage Results window opens.

    This window shows the extent to which method was tested.

See Also

Concepts

Anatomy of a Unit Test

Unit Tests For Generic Methods

Unit Tests for ASP.NET Web Services

Other Resources

Unit Tests and C++

How to: Add Web Performance, Unit and Coded UI Tests to a Load Test Scenario Using the Load Test Editor

How to: Remove Web Performance Tests, Unit and Coded UI Tests from a Load Test Scenario Using the Load Test Editor