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. 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: Generate 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.
///</summary>
public TestContext TestContext
{
    get
    {
        return testContextInstance;
    }
    set
    {
        testContextInstance = value;
    }
}

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

See Also

Tasks

How to: Generate a Unit Test
How to: Author a Unit Test

Reference

TestContext

Concepts

Testing Web Services
Coding a Data-Driven Unit Test
Testing Web Sites and Web Services in a Team Environment

Other Resources

Working with ASP.NET Unit Tests