Null MockFileData makes EnumerateDirectories return false
Drop the following test in MockDirectoryTests.cs and see it fail.
[Test]
public void MockDirectory_EnumerateDirectories_WithNoData_ShouldReturnDirectory()
{
// Arrange
var fileSystem = new MockFileSystem();
// Normally one would use `new MockFileData(string.Empty));` but I use `null`.
fileSystem.AddFile(XFS.Path(@"C:\Folder\bar"), null); // <----- there is the culprit
// Act
var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"c:\"), "Folder");
// Assert
// This assertion should succeed but fails.
Assert.That(actualResult.Count(), Is.EqualTo(1));
}
I tracked it to class MockFileSystem, method AllDirectories.
public IEnumerable<string> AllDirectories
{
get
{
lock (files)
{
return files.Where(f => f.Value.IsDirectory).Select(f => f.Key).ToArray();
}
}
}
where f.Value.IsDirectory fails due to Value being null.
Method Exists then handles any exceptions and returns false.
I have verified that if one has a real folder with a file of length 0, the folder will be returned when System.IO.Directory.EnumerateDirectories is called. At least on Windows10.
An easy solution would be to throw a NullArgumentException when AddFile is called without MockFileData but I am not in the position to deem it the correct one. This might be a breaking change.
Another solution could be to mockFile = mockFile ?? new MockFileData(string.Empty); in method AddFile.
A third solution could be to update the failing code with f.Value?.IsDirectory??true but that might have side effects.
Thanks for reporting! The second option (defensively default to an empty file for this case) sounds like the right thing to do.
Just ran into something similar, thought I'd add a comment to see what your thoughts are. (using 3.0.2)
The code that errors:
private IFileSystem GetMockFileSystem(string file, string existingBody = null)
{
return new MockFileSystem(
new Dictionary<string, MockFileData>
{
{ file, new MockFileData(existingBody) }
});
}
This option works fine:
private IFileSystem GetMockFileSystem(string file, string existingBody = null)
{
return new MockFileSystem(
new Dictionary<string, MockFileData>
{
{ file, existingBody }
});
}
Seems logical as the file wouldn't contain null, but thought I'd mention it in case it helps anyone else or if you would want to support that semi-illogical usage.