Using TestContext in Unit Tests

Most people don't know about the TestContext object, as it is not one regularly used. However, it can be very handy.

Data-Driven Unit Testing

The TestContext object's primary purpose IMO is for linking up a unit test with data rows from a data source. If you haven't checked out the data-driven unit test feature, take a look here. When it comes time to modify your code to pick up the data rows, you'll use the TestContext object as documented here.

It is important to create a private instance of the TestContext object in your TestClass. You'll also need to create a public property on that field, so the test harness can initialize it for you. If you create unit tests by way of Code Generation, then this object will be added for you automatically. Otherwise you will need to add it manually. That will look something like this (C#):
private TestContext m_testContext; public TestContext TestContext { get { return m_testContext; } set { m_testContext = value; } }

When you are ready to write your code, refer to the data through the TestContext object like (C#):
string firstParameter = m_testContext.DataRow[0].ToString(); string secondParameter = m_testContext.DataRow["SecondColumn"].ToString();
Note that you can refer to the column by index (zero-based) or by name.

Finding Files

Another great use for this object is determining where your tests and files have been deployed to. The TestContext.TestDeploymentDir property contains this information. There is also TestContext.TestLogsDir, TestContext.TestDir, and even TestContext.TestName. To see what these equate to, add a new unit test and add the following lines:
Console.WriteLine("TestDir: {0}", m_testContext.TestDir); Console.WriteLine("TestDeploymentDir: {0}", m_testContext.TestDeploymentDir); Console.WriteLine("TestLogsDir: {0}", m_testContext.TestLogsDir); Console.WriteLine("TestName: {0}", m_testContext.TestName);

Look at the test result details for that test to see the values.