Tuesday, August 6, 2019

C# - Unit Testing - How to write Data Driven Unit Test in C#

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


Unit Test Data Source


Here is an example to read CSV File (Persons.csv) in unit test.

CSV File:

File Location: Data\Persons.csv
  
Data Driven Unit Test in C#


Persons.csv:

Data Driven Unit Test in C#


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:
 
Data Driven Unit Test Result  in C#
Happy Testing !!

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...