It is common to use Directory.GetFiles from the System.IO. But it’s a bad habbit! We should be able to Unit Test our methods. Here is a simple way to do it. In this article I will use MOQ, if you don’t know it, please check this post about Unit Testing with MOQ.

Instead of using direclty the static method Directory.GetFiles, we should create our own implementation. No worries, we will actually use Directory.GetFiles, but with our implementation, we will be able to mock files in our Unit Tests. If you don’t know Moq please have a look here.

Let’s start with the interface:

using System.Collections.Generic; namespace MockFiles { public interface IDirectoryHelper { ICollection<string> GetFiles(string path); } }
Code language: C# (cs)

And now the implementation of IDirectoryHelper:

using System.Collections.Generic; using System.IO; namespace MockFiles { public class DirectoryHelper : IDirectoryHelper { public ICollection<string> GetFiles(string path) { string[] files = Directory.GetFiles(path); return files; } } }
Code language: C# (cs)

Now in our ConsoleApp, we will test it to be sure we get the local files as they are on the disk:

using System; using System.Collections.Generic; namespace MockFiles { class Program { static void Main(string[] args) { IDirectoryHelper directoryHelper = new DirectoryHelper(); ICollection<string> files = directoryHelper.GetFiles(@"C:\"); foreach (var file in files) Console.WriteLine(file); Console.WriteLine("\r\nPress any key..."); Console.ReadKey(); } } }
Code language: C# (cs)

As a result, you should see the local files on your disk under C:\.

But now, we can do a Unit Test where we want to simulate some files:

using Microsoft.VisualStudio.TestTools.UnitTesting; using MockFiles; using Moq; using System.Collections.Generic; namespace UnitTests { [TestClass] public class UnitTest1 { private IDirectoryHelper _directoryHelper; private readonly string _file1 = "test1.txt"; private readonly string _file2 = "test2.txt"; [TestInitialize] public void Initialize() { _directoryHelper = Mock.Of<IDirectoryHelper>(); Mock.Get(_directoryHelper) .Setup(x => x.GetFiles(It.IsAny<string>())) .Returns((string x) => new List<string> { _file1, _file2 }); } [TestMethod] public void GetFiles_Test() { ICollection<string> files = _directoryHelper.GetFiles(@"C:\"); Assert.IsNotNull(files); Assert.IsTrue(files.Count == 2); Assert.IsTrue(files.Contains(_file1)); } } }
Code language: C# (cs)

Happy coding! 🙂