Skip to content

Latest commit

 

History

History
241 lines (197 loc) · 8.58 KB

File metadata and controls

241 lines (197 loc) · 8.58 KB

System.IO.Abstractions NuGet Build Quality Gate Status Coverage Renovate enabled FOSSA Status

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.

Usage

dotnet add package TestableIO.System.IO.Abstractions.Wrappers

Note: This NuGet package is also published as System.IO.Abstractions but we suggest to use the prefix to make clear that this is not an official .NET package.

public class MyComponent
{
    readonly IFileSystem fileSystem;

    // <summary>Create MyComponent with the given fileSystem implementation</summary>
    public MyComponent(IFileSystem fileSystem)
    {
        this.fileSystem = fileSystem;
    }
    /// <summary>Create MyComponent</summary>
    public MyComponent() : this(
        fileSystem: new FileSystem() //use default implementation which calls System.IO
    )
    {
    }

    public void Validate()
    {
        foreach (var textFile in fileSystem.Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly))
        {
            var text = fileSystem.File.ReadAllText(textFile);
            if (text != "Testing is awesome.")
                throw new NotSupportedException("We can't go on together. It's not me, it's you.");
        }
    }
}

Test helpers

The library also ships with a series of test helpers to save you from having to mock out every call, for basic scenarios. They are not a complete copy of a real-life file system, but they'll get you most of the way there.

dotnet add package TestableIO.System.IO.Abstractions.TestingHelpers

Note: This NuGet package is also published as System.IO.Abstractions.TestingHelpers but we suggest to use the prefix to make clear that this is not an official .NET package.

[Test]
public void MyComponent_Validate_ShouldThrowNotSupportedExceptionIfTestingIsNotAwesome()
{
    // Arrange
    var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
    {
        { @"c:\myfile.txt", new MockFileData("Testing is meh.") },
        { @"c:\demo\jQuery.js", new MockFileData("some js") },
        { @"c:\demo\image.gif", new MockFileData(new byte[] { 0x12, 0x34, 0x56, 0xd2 }) }
    });
    var component = new MyComponent(fileSystem);

    try
    {
        // Act
        component.Validate();
    }
    catch (NotSupportedException ex)
    {
        // Assert
        Assert.That(ex.Message, Is.EqualTo("We can't go on together. It's not me, it's you."));
        return;
    }

    Assert.Fail("The expected exception was not thrown.");
}

We even support casting from the .NET Framework's untestable types to our testable wrappers:

FileInfo SomeApiMethodThatReturnsFileInfo()
{
    return new FileInfo("a");
}

void MyFancyMethod()
{
    var testableFileInfo = (FileInfoBase)SomeApiMethodThatReturnsFileInfo();
    ...
}

Mock support

Since version 4.0 the top-level APIs expose interfaces instead of abstract base classes (these still exist, though), allowing you to completely mock the file system. Here's a small example, using Moq:

[Test]
public void Test1()
{
    var watcher = Mock.Of<IFileSystemWatcher>();
    var file = Mock.Of<IFile>();

    Mock.Get(file).Setup(f => f.Exists(It.IsAny<string>())).Returns(true);
    Mock.Get(file).Setup(f => f.ReadAllText(It.IsAny<string>())).Throws<OutOfMemoryException>();

    var unitUnderTest = new SomeClassUsingFileSystemWatcher(watcher, file);

    Assert.Throws<OutOfMemoryException>(() => {
        Mock.Get(watcher).Raise(w => w.Created += null, new System.IO.FileSystemEventArgs(System.IO.WatcherChangeTypes.Created, @"C:\Some\Directory", "Some.File"));
    });

    Mock.Get(file).Verify(f => f.Exists(It.IsAny<string>()), Times.Once);

    Assert.True(unitUnderTest.FileWasCreated);
}

public class SomeClassUsingFileSystemWatcher
{
    private readonly IFileSystemWatcher _watcher;
    private readonly IFile _file;

    public bool FileWasCreated { get; private set; }

    public SomeClassUsingFileSystemWatcher(IFileSystemWatcher watcher, IFile file)
    {
        this._file = file;
        this._watcher = watcher;
        this._watcher.Created += Watcher_Created;
    }

    private void Watcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        FileWasCreated = true;

        if(_file.Exists(e.FullPath))
        {
            var text = _file.ReadAllText(e.FullPath);
        }
    }
}

MockFileSystem Events

The MockFileSystem in the testing helpers now supports an event system that allows you to observe file system operations and simulate errors:

[Test]
public void Test_SimulateDiskFullError()
{
    var fileSystem = new MockFileSystem(new MockFileSystemOptions { EnableEvents = true });
    
    using (fileSystem.Events.Subscribe(FileOperation.Write, args =>
    {
        if (args.Phase == OperationPhase.Before)
        {
            args.SetResponse(new OperationResponse 
            { 
                Exception = new IOException("There is not enough space on the disk.") 
            });
        }
    }))
    {
        Assert.Throws<IOException>(() => fileSystem.File.WriteAllText(@"C:\test.txt", "content"));
    }
}

[Test]
public void Test_TrackFileOperations()
{
    var fileSystem = new MockFileSystem(new MockFileSystemOptions { EnableEvents = true });
    var operations = new List<string>();
    
    using (fileSystem.Events.Subscribe(args =>
    {
        if (args.Phase == OperationPhase.After)
        {
            operations.Add($"{args.Operation} {args.Path}");
        }
    }))
    {
        fileSystem.File.Create(@"C:\test.txt").Dispose();
        fileSystem.File.WriteAllText(@"C:\test.txt", "content");
        fileSystem.File.Delete(@"C:\test.txt");
        
        Assert.That(operations, Is.EqualTo(new[] {
            "Create C:\\test.txt",
            "Write C:\\test.txt", 
            "Delete C:\\test.txt"
        }));
    }
}

[Test]
public void Test_SimulateFileInUse()
{
    var fileSystem = new MockFileSystem(new MockFileSystemOptions { EnableEvents = true });
    fileSystem.AddFile(@"C:\locked.db", "data");
    
    // Simulate file locking for .db files
    using (fileSystem.Events.Subscribe(args =>
    {
        if (args.Phase == OperationPhase.Before && 
            args.Path.EndsWith(".db") && 
            args.Operation == FileOperation.Delete)
        {
            args.SetResponse(new OperationResponse 
            { 
                Exception = new IOException("The file is in use.") 
            });
        }
    }))
    {
        var exception = Assert.Throws<IOException>(() => fileSystem.File.Delete(@"C:\locked.db"));
        Assert.That(exception.Message, Is.EqualTo("The file is in use."));
    }
}

The event system is opt-in and has almost zero overhead when not enabled. Enable it by setting EnableEvents = true in MockFileSystemOptions.

Related projects