Simple C# data driven unit test with csv

In this blog, I wanted to address the problem how we can do data driven testing with csv files in C# unit tests.

We can do looping of for different data sets for sequential data. (Each iteration of test for each row in the data in csv file).

 private TestContext testContext;
 public TestContext TestContext {

 get { return testContext; }
 set { testContext = value; }

 }

For the unit tests in MS Test Frame work, we need to define the testing context,

and the context will return the current context.

Lets see how we can loop taking the example of Calculator class.

Lets assume Calculator class having all methods corresponding to do user actions.

 public UITest Calculator = new UITest();

Lets see how we can use data source, we can do by following code.

 [TestMethod]
 [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV",
 @"|DataDirectory|\data\data.csv", "data#csv", DataAccessMethod.Sequential)]

We can use DataSoruce tag for the data source such as CSV or excel. Its better to use CSV files.

Most often we get error for missing reference. See that you have “System.Data” reference in the project setup.

data

Lets look at the actual implementation and the data structure in the project explorer.

explorer

The data csv contains following for illustration.

datacsv

Following is the test written.

TheTest

We can use Test Explorer to execute it which will produce results for each row.

There by we can get insight of which one got failed.TestResults

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s