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 Visual Studio Team System 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 list, run a test, and read code coverage results.

Do you like this topic? This topic has more information in a single place than our typical topic does. If you like it, or even if you don't, please click the stars in the upper right of your help screen to let us know what you think. One star means you don't like it, five stars means you like it a lot.

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, which 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 there are changes made 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 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 Visual Studio Team System 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 a default.aspx page. If you create a unit test for a Web service in a project that does not contain a default.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 click Create Unit Tests.

    — or —

    In the case of an ASP.NET Web service, open the App_Code folder for the project with the service you want to test, open the <ServiceName>.cs file, and right-click anywhere in that file.

  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 allow you to customize how your test files, test classes, and test methods are named when you generate unit tests.

    • Mark all test results Inclusive 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 generation warnings: This check box is no longer an active feature.

    • 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 allow 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 Assemblies. For more information, see How to: Create a Unit Test without Source Code.

  7. In the Output project box, use one of the following procedures:

    • 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 if the method behaves as expected. To make the test meaningful, you have to initialize the variables. Also, to allow the results of the test to be reported to you, you have to replace the placeholder Assert statement with one that is appropriate for that method, which is often the Assert.AreEqual statement.

To add validation to your unit test

  1. Open the unit test file that contains your unit test, and then 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 List

Test Lists are a way of collecting 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 Using Test Lists.

To create a test list

  1. On the Test menu, click Create New Test List. The Create New Test List dialog box opens on top of the Test List Editor window.

  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 any time that you want. 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 Selected Tests.

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 Run Configurations, and click the configuration for your current test run.

    2. In the <testrunname>.testrunconfig dialog box, click Code Coverage in the list and then select the check box or boxes to select items for which to collect code coverage information.

    3. 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, double-click the test in the Test Results window.

  6. (Optional) To locate the area of your unit test file that contains an error, in the Error List, double-click the error.

For more information about understanding your test results, see Obtaining Test Results.

(Optional) View Code Coverage

After you run a unit test, if you chose to edit the test run configuration when you ran the test, 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 on 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.

  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 and C++

Unit Tests and Generics

Unit Tests for ASP.NET Web Services