Data driven unit tests with Filenames from a directory!


How to create simple data-driven-unit-tests with files from directories

Create the following folders in your solution
\files\valid\
\files\invalid\


copy in those folders your single files to test.
e.g. copy your valid testfiles (that are valid items for a test) to \files\valid\
and yout invalid testfiles to \files\invalid\




Problem

there is no dataprovider (DataSource) for directories (not in vs2005, in vs2008 im not sure)
create in each folder a text file.
\files\valid\data.txt
\files\invalid\data.txt

these text files will contain a directory listing with the single files!

add to your unit test

[DeploymentItem(@"files\invalid\data.txt", @"invalid")]
[DataSource("System.Data.OleDb", @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\files\invalid;Extended Properties='text;FMT=Delimited'", @"data.txt", DataAccessMethod.Sequential)]

now you will get in your unit test the single files
string fileName = TestContext.DataRow[0].ToString();



but how to fill the files data.txt?
use this method in Assembly Initialization

       [AssemblyInitialize]
       public static void CreateOutputDataTxtFiles(TestContext context)
       {
          
           string startDir = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(context.TestDir)), @"Siag.XXX.BusinessLogic.Test");
           string addDir = @"files\valid";

           WriteFilePathsToData(Path.Combine(startDir, addDir), "*.dat");

           addDir = @"files\invalid";

           WriteFilePathsToData(Path.Combine(startDir, addDir), "*.dat");

       }


       private static void WriteFilePathsToData(string startDir, string searchPattern)
       {
           StringBuilder result = new StringBuilder();

           foreach (string fileName in Directory.GetFiles(startDir, searchPattern))
           {
               result.AppendLine(fileName);
           }

           // add additional directories here

           string fileNameData = Path.Combine(startDir, @"data.txt");

           File.SetAttributes(fileNameData, FileAttributes.Normal);
           File.WriteAllText(fileNameData, result.ToString());
       }

Latest Posts

Popular Posts