Data Driven Unit Tests

How to use a CSV file to test different scenarios with a Unit Test ?

How to achieve positive and negative testing ? In this case, I will check possible exception thrown by code within the same unit test.

Class to Test :

1
2
3
4
5
6
7
public class MyMath
{
    public int Divide(int a, int b)
    {
        return a / b;
    }
}

CSV File : (Warning : Make sure the file is saved as ASCII. If saved as UTF-8, Byte order Mark will be an issue and the first column name will be incorrect.) (Note: Make sure the csv file is marked as Deploy Always)

    a, b, expected, error
    1,1,1,""
    10,5,2,""
    5,0,0,"System.DivideByZeroException"

Unit Test :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Dummy;

namespace UnitTests
{
    [TestClass]
    public class MathTest
    {
        private TestContext testContextInstance;
        public TestContext TestContext
        {

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

        }

        [DataSource(@"Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\TestDivision.csv", "TestDivision#csv", DataAccessMethod.Sequential), DeploymentItem("TestLists\\TestDivision.csv")]
        [TestMethod]
        public void TestDataDivision()
        {
            string expectedError = testContextInstance.DataRow["error"].ToString();

            try
            {
                int a = int.Parse(TestContext.DataRow["a"].ToString());
                int b = int.Parse(TestContext.DataRow["b"].ToString());
                int expectedResult = int.Parse(TestContext.DataRow["expected"].ToString());

                MyMath sut = new MyMath();
                Assert.IsTrue(expectedResult == sut.Divide(a, b));
            }
            catch (Exception e)
            {
                Assert.AreEqual(expectedError, e.GetType().ToString());
            }
        }
    }
}