TestContext in Data Driven Unit Tests

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.

UserContact Table Definition

After creating a table, we add few users data in the table: UserContact, as shown below.

Data in UserContact Table

Next, we show how TestContext enables us to access row stored in the UserContact table in the following unit test.

[DataSource("System.Data.SqlClient", "[path to MDF]";
Integrated Security=True;User Instance=True", "UserContact",
DataAccessMethod.Sequential), TestMethod()]
public void ShouldCreateUsers(){
string userLoginName = (TestContext.DataRow["LoginName"].ToString());
string userFirstName = (TestContext.DataRow["FirstName"].ToString());
string userLastName = (TestContext.DataRow["LastName"].ToString());
string userEmailAddress = (TestContext.DataRow["EmailAddress"].ToString());
string userDepartment = (TestContext.DataRow["Department"].ToString());
TestContext.WriteLine("Creating user - Login Name :{0} Name : {1} {2} EmailAddress : {3} ", userLoginName, userFirstName,userLastName, userEmailAddress);
bool successful = UserManger.CreateUser(userLoginName, userFirstName, userLastName, userEmailAddress, userDepartment);
Assert.IsTrue(successful);
}
view raw gistfile1.cs hosted with ❤ by GitHub

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 DataRow.

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.

Related Posts

Other posts of the series are outlined below.

On Unit Testing:

Usage of TestContext:

Leave a comment

Design a site like this with WordPress.com
Get started