TestContext consolidates the support of Data Driven Unit Tests via mstest by allowing access to the datasource (e.g., database table), associated with the present code under test. This post describes this very feature of TestContext.
We illustrate this feature with a simple and contrived example (devised only for illustrative purpose), which verify
CreateUser API of the application under test. So, we first create a datasource, which is a table that stores contact information.
After creating a table, we add few users data in the table:
UserContact, as shown below.
Next, we show how
TestContext enables us to access row stored in the
UserContact table in the following unit test.
In this example, we can see that in (line 5 – 10 ),
TestContext is providing us access to the current
DataRow for which the unit test is getting executed. During execution, we can see the output of
TestContext.Writeline(line 12), and the result of the unit test for each
To sum up, in this post, we discussed the usage of TestContext in the context of Data Driven Unit Tests. It effectively allows us to access all the DataRows in the test Tables and hence, plays an instrumental role in this context. Thanks.
Other posts of the series are outlined below.
On Unit Testing:
Usage of TestContext: