Skip to content

Commit 4856de0

Browse files
authored
Support creating files from relative paths (#615)
1 parent 11dd7f6 commit 4856de0

2 files changed

Lines changed: 23 additions & 5 deletions

File tree

System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
using System.Collections.Generic;
2-
using NUnit.Framework;
2+
using NUnit.Framework;
33
using System.Text;
44

55
namespace System.IO.Abstractions.TestingHelpers.Tests
@@ -52,20 +52,20 @@ public void MockFileStreamFactory_CreateForAnExistingFile_ShouldReplaceFileConte
5252
var fileSystem = new MockFileSystem();
5353
string FilePath = XFS.Path("C:\\File.txt");
5454

55-
using(var stream = fileSystem.FileStream.Create(FilePath, fileMode, System.IO.FileAccess.Write))
55+
using (var stream = fileSystem.FileStream.Create(FilePath, fileMode, System.IO.FileAccess.Write))
5656
{
5757
var data = Encoding.UTF8.GetBytes("1234567890");
5858
stream.Write(data, 0, data.Length);
5959
}
6060

61-
using(var stream = fileSystem.FileStream.Create(FilePath, fileMode, System.IO.FileAccess.Write))
61+
using (var stream = fileSystem.FileStream.Create(FilePath, fileMode, System.IO.FileAccess.Write))
6262
{
6363
var data = Encoding.UTF8.GetBytes("AAAAA");
6464
stream.Write(data, 0, data.Length);
6565
}
6666

6767
var text = fileSystem.File.ReadAllText(FilePath);
68-
Assert.AreEqual("AAAAA", text);
68+
Assert.AreEqual("AAAAA", text);
6969
}
7070

7171
[Test]
@@ -117,5 +117,22 @@ public void MockFileStreamFactory_CreateExistingFile_Should_Throw_IOException(Fi
117117
Assert.Throws<IOException>(() => fileStreamFactory.Create(XFS.Path(@"C:\Test\some_random_file.txt"), fileMode));
118118

119119
}
120+
121+
[Test]
122+
[TestCase(FileMode.Create)]
123+
[TestCase(FileMode.CreateNew)]
124+
[TestCase(FileMode.OpenOrCreate)]
125+
public void MockFileStreamFactory_CreateWithRelativePath_CreatesFileInCurrentDirectory(FileMode fileMode)
126+
{
127+
// Arrange
128+
var fileSystem = new MockFileSystem();
129+
130+
// Act
131+
var fileStreamFactory = new MockFileStreamFactory(fileSystem);
132+
fileStreamFactory.Create("some_random_file.txt", fileMode);
133+
134+
// Assert
135+
Assert.True(fileSystem.File.Exists(XFS.Path("./some_random_file.txt")));
136+
}
120137
}
121138
}

System.IO.Abstractions.TestingHelpers/MockFileStream.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,8 @@ public MockFileStream(
6868
}
6969
else
7070
{
71-
if (!mockFileDataAccessor.Directory.Exists(mockFileDataAccessor.Path.GetDirectoryName(path)))
71+
var directoryPath = mockFileDataAccessor.Path.GetDirectoryName(path);
72+
if (!string.IsNullOrEmpty(directoryPath) && !mockFileDataAccessor.Directory.Exists(directoryPath))
7273
{
7374
throw CommonExceptions.CouldNotFindPartOfPath(path);
7475
}

0 commit comments

Comments
 (0)