Search code examples
c#unit-testingfile-iodependency-injectionnunit

Unit Testing File I/O


Reading through the existing unit testing related threads here on Stack Overflow, I couldn't find one with a clear answer about how to unit test file I/O operations. I have only recently started looking into unit testing, having been previously aware of the advantages but having difficulty getting used to writing tests first. I have set up my project to use NUnit and Rhino Mocks and although I understand the concept behind them, I'm having a little trouble understanding how to use Mock Objects.

Specifically I have two questions that I would like answered. First, what is the proper way to unit test file I/O operations? Second, in my attempts to learn about unit testing, I have come across dependency injection. After getting Ninject set up and working, I was wondering whether I should use DI within my unit tests, or just instantiate objects directly.


Solution

  • Check out Tutorial to TDD using Rhino Mocks and SystemWrapper.

    SystemWrapper wraps many of System.IO classes including File, FileInfo, Directory, DirectoryInfo, ... . You can see the complete list.

    In this tutorial I'm showing how to do testing with MbUnit but it's exactly the same for NUnit.

    Your test is going to look something like this:

    [Test]
    public void When_try_to_create_directory_that_already_exists_return_false()
    {
        var directoryInfoStub = MockRepository.GenerateStub<IDirectoryInfoWrap>();
        directoryInfoStub.Stub(x => x.Exists).Return(true);
        Assert.AreEqual(false, new DirectoryInfoSample().TryToCreateDirectory(directoryInfoStub));
    
        directoryInfoStub.AssertWasNotCalled(x => x.Create());
    }