driving data driven unit tests with text files

A few weeks ago I was looking for a simple way to do data driven unit tests on VS 2005 using a plain text file with one entry per line as the data source.  I waded through documentation and forum posts using every search trick I know to find a solution.   Nothing jumped out at me, so here’s what I pieced together:

1)      Add a reference to System.Data in your unit test assembly. 

2)      Add the text file to the solution (eg, data.txt) then Right Click->Properties->set Copy to Output Directory = “Copy always” or “Copy if newer”  — in this example the text file consists of 10 lines of the word “hi” each on its own line.   This is in honor of a 10 year old I know who says “hi hi hi hi hi” whenever things get too boring.  Change one of the values to “bye” instead of “hi” and the unit test will fail.

3)      Plop this code into your unit test assembly:

        private TestContext m_testContext;

        public TestContext TestContext


            get { return m_testContext; }

            set { m_testContext = value; }





        [DataSource(“System.Data.OleDb”, “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.;Extended Properties=’text;FMT=Delimited'”, “data.txt”, DataAccessMethod.Sequential)]

        public void SayHi()


            //replace next line with a call to your code under test

            if ((“hi” != (string)TestContext.DataRow[0] ))


                Assert.Fail(“value = “ + (string)TestContext.DataRow[0]);



Once the unit test has finished executing you can double click on the result and it will present you with an itemized breakdown of the results in a tabular format.  The failure message will be included, so the more meaningful, the better.

In full disclosure, after all was said and done, I didn’t actually use this for the problem I was trying to solve.  One drawback to this approach for me was the granularity of the reporting during runtime, since you don’t get the breakdown report or status summary until after the entire unit test is completed.  With over 6,000 test values to feed into an already slow test function, it would have taken over 20 hours to run just one unit test.  In this particular case I actually put together a code generator to turn it into 6000+ individual TestMethods and using partial classes it compiles right into the test assembly without a lot of hassle. 

Comments (0)