Visual Studio 2010 - Data Driven Unit Test



This article is a continuation of the earlier article "Visual Studio 2010 Tools - To improve code quality". Here I am going to demo data driven unit testing using a CSV file. Ultimately we are going to put test data into a CSV file and use that file data as an input for unit testing.

Please refer to my earlier article:

http://www.c-sharpcorner.com/UploadFile/sanks/1733/Default.aspx

Step 1: View Unit Test Code

Here we have a MathLibrary project having Add, Multiply, Divide and Subtract methods in the CalculateBasic.cs class file. In the MathUnitTest project we have CalculateBasicTest.cs file for unit testing.

DDT1.gif

We are going to do a data driven unit test on the following MultiplyNumbers method.

DDT2.gif

The following is the Unit Test code for the above method.

DDT3.gif

Step 2: Create CSV file

To add a new CSV file to the Unit Test Project, right-click the MathUnitTest project and click Add -> New Item.

DDT4.gif

Select Text File and name it MultiplyTestData.csv.

DDT5.gif

Step 3: Add data to CSV file

As shown below the file is created; then enter test data as shown. As shown the CSV file, Number1 and Number 2 are input parameters and Total is the result of multiplication of Number1 and Number2.

DDT6.gif

Step 4: Set CSV file property

Right-click the MultiplyTestData.csv file and click properties. Select the Copy always option as shown below so that the file is copied to the bin folder after build.

DDT7.gif

Step 5: View Change Attribute of test method

To use the CSV file as an input for test data:

  1. Change the attribute of the MultiplyNumbersTest method as shown below
  2. Change the value assigned to Number1, Number2, expected as shown below. Here TextContext.DataRow[0] is the first column in the CSV file.

    DDT8.gif
Step 6: Enable Deployment setting

Before running the Unit Test, click on Test -> Edit Test Settings -> Local (local.testsettings) as shown above. The following screen pops up and makes sure that Deployment Enable deployment is checked.

DDT10.gif

Step 7: Run Unit Test

Click on Test -> Window -> Test Impact View to view the test impact window. Then build the solution. The following screen is shown. Here in the code changes section we can see MultiplyNumbersTest method. Right-click and select Run Impacted Tests.

DDT11.gif

As shown below, the test is passed. Double-click on a Passed test in the Test Results window; it shows that all 3 rows from the CSV test has passed.

DDT12.gif

Conclusion: Using a CSV file, one can do Data driven Unit Testing. Here the advantage is we can test for all possible values and can also check the code coverage.


Similar Articles