Data-driven testing in NUnit?

Nobody picture Nobody · Oct 27, 2010 · Viewed 22.5k times · Source

In MSTest you can do something like:

[TestMethod]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", 
            "testdata.csv", "testdata#csv", DataAccessMethod.Sequential)]
public void TestSomething()
{
    double column1 = Convert.ToDouble(TestContext.DataRow["column1"]);
    ...
    Assert.AreEqual(...);
}

What is the equivalent code in NUnit 2.5?

Answer

Tim Abell picture Tim Abell · May 23, 2011

I got csv based data driven testing in NUnit working as follows:

Use the csv reader from code project, wrapped up in a private method returning IEnumerable in your test class, and then reference this with a TestCaseSource attribute on your test cases. Include your csv file in your project and set "Copy to Output Directory" to "Copy Always".

using System.Collections.Generic;
using System.IO;
using LumenWorks.Framework.IO.Csv;
using NUnit.Framework;

namespace mytests
{
    class MegaTests
    {
        [Test, TestCaseSource("GetTestData")]
        public void MyExample_Test(int data1, int data2, int expectedOutput)
        {
            var methodOutput = MethodUnderTest(data2, data1);
            Assert.AreEqual(expectedOutput, methodOutput, string.Format("Method failed for data1: {0}, data2: {1}", data1, data2));
        }

        private int MethodUnderTest(int data2, int data1)
        {
            return 42; //todo: real implementation
        }

        private IEnumerable<int[]> GetTestData()
        {
            using (var csv = new CsvReader(new StreamReader("test-data.csv"), true))
            {
                while (csv.ReadNextRecord())
                {
                    int data1 = int.Parse(csv[0]);
                    int data2 = int.Parse(csv[1]);
                    int expectedOutput = int.Parse(csv[2]);
                    yield return new[] { data1, data2, expectedOutput };
                }
            }
        }
    }
}

original post at: http://timwise.blogspot.com/2011/05/data-driven-test-in-nunit-with-csv.html