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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值