Ninja Nichols

The discipline of programming

Unit Testable System.IO (C#)

It seems the hardest part of writing good unit tests is trying to mock out third-party dependencies.

A surprising number of the core Microsoft libraries like System.IO simply aren’t unit testable, so I was almost unreasonably happy when I stumbled upon System.IO.Abstractions, which describes itself as “Just like System.Web.Abstractions, but for System.IO. Yay for testable IO access!”.

From their documentation:

At the core of the library is IFileSystem and FileSystem. Instead of calling methods like File.ReadAllText directly, use IFileSystem.File.ReadAllText. We have exactly the same API, except that ours is injectable and testable.

Looks like it’s being actively maintained. Just use NuGet to add it your project:

PM> Install-Package System.IO.Abstractions