40

Using Nunit, I want to be able to write a test fixture that will read all the filenames in a particular directory and create a test for each file.

I could quite easily write one test method that scans through the directory and just does all the tests, but when I run NUnit I want to be able to see each of the tests individually.

Is this even possible?

Ray
  • 45,695
  • 27
  • 126
  • 169

4 Answers4

66

I've found a way that fits my purposes

Have one test case, and mark it with the TestCaseSource attribute like so

[Test, TestCaseSource("GetTestCases")]
public void TestFile(string filename)
{
    //do test
}

Then write the GetTestCases to read all the file names in the directory

private static string[] GetTestCases()
{
    return GetAllFilesInCurrentDirectory();
}

Then when I start NUnit I get a list of the tests to be run (listed under TestFile).

Ray
  • 45,695
  • 27
  • 126
  • 169
  • Nice and simple. The attribute is also fairly flexible, as described in the docs (referring to v2.5.2) here: http://nunit.com/index.php?p=testCaseSource&r=2.5.2 – Mal Ross Nov 20 '09 at 09:44
  • NUnit rocks!! It made things simpler. I'm using this feature for integration tests – AksharRoop Aug 14 '14 at 06:07
  • How to make it working in ReSharper test runner? It shows errors and fails in message boxes instead of displaying stack in testing session – moudrick May 18 '16 at 10:10
  • @moudrick - You might want to make a new question specific to Resharper. A comment on a 7 year old answer is not going to get a response. – Ray Jun 19 '16 at 22:32
  • 1
    worth using nameof(GetTestCases) to make your test refactor friendly – Dav Evans Sep 07 '17 at 06:15
3

Try the data driven test cases NUnit extension.

dbkk
  • 12,643
  • 13
  • 53
  • 60
1

If you are not going to be adding files to that directory over time and have a set of filenames to pass in as an input to a generic test, try using the RowTest NUnit extension (part of the std distrib post v2.4.7) - You'd be able to see each test case - input combination individually in the GUI grouped under a single node.

If you are going to be adding files to that directory, I'd write a single NUnit TestCase that loops over a list of files obtained at runtime and calls the generic test method with each filepath. Use a collecting parameter to collect failing test file names - at the end you assert. You wouldn't be able to see each test case individually but you'd have readable simple test code.

Assert.AreEqual(listOfFailedFiles.Length, 0, PrettyPrint(listOfFailedFiles))
Gishu
  • 134,492
  • 47
  • 225
  • 308
0

I know this is a little obscure but I have used a script in the past to generate code for me which I can then execute as individual test cases.

benPearce
  • 37,735
  • 14
  • 62
  • 96