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.
Lets look at the actual implementation and the data structure in the project explorer.
The data csv contains following for illustration.
Following is the test written.
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.