Using the TestContext Class
You use the TestContext class in unit tests for any of several purposes. These are its most frequent uses:
In any unit test, because the TestContext class stores information that is provided to unit tests, such as the path to the deployment directory. For more information, see Structure of Unit Tests.
In unit tests to test Web services that run on ASP.NET Development Server. In this case, TestContext stores the URL of the Web service. For more information, see Testing Web Services.
In ASP.NET unit tests, to obtain access to the Page object. For more information, see Working with ASP.NET Unit Tests.
In data-driven unit tests, the TestContext class is required because it provides access to the data row. For more information, see Working with Data-Driven Unit Tests , Coding a Data-Driven Unit Test, and Walkthrough: Using a Configuration File to Define a Data Source.
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
Concepts
Testing Web Services
Coding a Data-Driven Unit Test
Testing Web Sites and Web Services in a Team Environment