Using the TestContext Class

You use the TestContext class in unit tests for any of several purposes. These are its most frequent uses:

Obtaining TestContext

When you run a unit test, you are automatically provided with a concrete instance of the TestContext type, if the test class that contains your unit test method has a TestContext property defined. The unit test framework automatically populates the members of TestContext for you to use throughout the duration of your tests. (For more information about the members of TestContext, see TestContext.) This means that you do not have to instantiate or derive the TestContext type in your code. You can just start using it; it has IntelliSense support.

Not every test class automatically has a TestContext property defined. Whether it does depends on how you created the test.

When the TestContext Property Is Automatically Defined

Generating a unit test from code automatically defines the TestContext property. For more information about the ways to generate unit tests, see How to: Create and Run a Unit Test.

When the TestContext Property Is Not Automatically Defined

You can create unit tests in several ways other than automatically generating them. Your test class does not automatically have a TestContext property defined if you create your test in any of these ways, which include the following:

  • Code a new test class by hand.

  • Add a new unit test file to the project. For example, you can do this by choosing the New Test option on the Test menu and then selecting Unit Test in the Add New Test dialog box.

In these cases, you must add the TestContext property manually. For more information about coding unit tests, see How to: Author a Unit Test.

TestContext Example

To use TestContext, create a member and property within your test class, as in the following example in C#.

private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
public TestContext TestContext
        return testContextInstance;
        testContextInstance = value;

The test framework automatically sets the property, which you can then use in unit tests.

See Also


How to: Author a Unit Test


How to: Create and Run a Unit Test

Unit Tests for Web Services

Data-Driven Unit Tests

Testing Web Sites and Web Services in a Team Environment



Other Resources

Working with ASP.NET Unit Tests