In this blog, we
will discuss how to write the data driven unit test in C# and read data from
csv file sequentially and iterate of unit test for each row.
Microsoft
Test Framework Provides the TestContext
object, which returns the current context 0f data means current iteration of data row.
[TestClass]
public class DataDriven_UnitTest
{
public TestContext TestContext { get; set; }
}
Microsoft
Test Framework provides DataSource Attribute which specifies connection string,
table name and row access method like random or
Sequentially
Here is an
example to read CSV File (Persons.csv) in unit test.
CSV File:
File
Location: Data\Persons.csv
Persons.csv:
Unit Test Class:
[TestClass]
public class DataDriven_UnitTest
{
public TestContext TestContext { get; set; }
[TestMethod]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV",
@"|DataDirectory|\Data\Persons.csv", "Persons#csv",
DataAccessMethod.Sequential)]
public void Verify_Person_Name()
{
string _firstName = TestContext.DataRow[0].ToString();
string _lastName =
TestContext.DataRow[1].ToString();
string _name = TestContext.DataRow[2].ToString();
Person person = new Person(_firstName, _lastName);
Assert.IsTrue(person.Name == _name);
}
}
The Data Row
object provides the collection of columns of current data row and you can read
each column value by passing Column Name or Column Index
By Column Name:
string
_firstName = TestContext.DataRow[FirstName].ToString();
By Column Index:
string
_firstName = TestContext.DataRow[0].ToString();
Here is
result of data driven unit test:
Happy Testing !!
No comments:
Post a Comment