Skip to content

DirectoryNotFound is not Thrown by MockFile Create #278

@wleader

Description

@wleader

I had added a test to my project where I wanted to make sure that my code would create the directory for an output file before writing the output file, this test passed, but when I went to run my code for real, I got a DirectoryNotFound exception. It turns out in my implementation, I had neglected to create the directory. When I investigated why my test reported that the directory was created, when there was no code to create the directory, I found the following.

my code gets an output stream by calling:

IFileSystem.File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.None);

When the test is running this calls System.IO.Abstractions.TestingHelpers.MockFile.Open.

In the MockFile implementation of open, it eventually calls:

if (mode == FileMode.Create || mode == FileMode.Truncate)
{
    Delete(path);
    return Create(path);
}

Looking at the Create function:

public override Stream Create(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path", "Path cannot be null.");
    }
    mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path");
    mockFileDataAccessor.AddFile(path, new MockFileData(new byte[0]));
    var stream = OpenWrite(path);
    return stream;
}

We see that this code doesn't check that the directory part of the path parameter exists. When AddFile is called, the directory gets added to the mock file systems known directories. I think this code should throw a DirectoryNotFound exception when the directory does not exist.

This appears to be similar to the issue described here:
#140

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions