I created an extension method to add all JSON configuration files to the IConfigurationBuilder
public static class IConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddJsonFilesFromDirectory(
this IConfigurationBuilder configurationBuilder,
IFileSystem fileSystem,
string pathToDirectory,
bool fileIsOptional,
bool reloadConfigurationOnFileChange,
string searchPattern = "*.json",
SearchOption directorySearchOption = SearchOption.AllDirectories)
{
var jsonFilePaths = fileSystem.Directory.EnumerateFiles(pathToDirectory, searchPattern, directorySearchOption);
foreach (var jsonFilePath in jsonFilePaths)
{
configurationBuilder.AddJsonFile(jsonFilePath, fileIsOptional, reloadConfigurationOnFileChange);
}
return configurationBuilder;
}
}
and want to create tests for it using xUnit. Based on
How do you mock out the file system in C# for unit testing?
I installed the packages System.IO.Abstractions and System.IO.Abstractions.TestingHelpers and started to test that JSON files from directories have been added
public sealed class IConfigurationBuilderExtensionsTests
{
private const string DirectoryRootPath = "./";
private readonly MockFileSystem _fileSystem;
public IConfigurationBuilderExtensionsTests()
{
_fileSystem = new MockFileSystem(new[]
{
"text.txt",
"config.json",
"dir/foo.json",
"dir/bar.xml",
"dir/sub/deeper/config.json"
}
.Select(filePath => Path.Combine(DirectoryRootPath, filePath))
.ToDictionary(
filePath => filePath,
_ => new MockFileData(string.Empty)));
}
[Theory]
[InlineData("*.json", SearchOption.AllDirectories)]
[InlineData("*.json", SearchOption.TopDirectoryOnly)]
// ... more theories go here ...
public void ItShouldAddJsonFilesFromDirectory(string searchPattern, SearchOption searchOption)
{
var addedJsonFilePaths = new ConfigurationBuilder()
.AddJsonFilesFromDirectory(_fileSystem, DirectoryRootPath, true, true, searchPattern, searchOption)
.Sources
.OfType<JsonConfigurationSource>()
.Select(jsonConfigurationSource => jsonConfigurationSource.Path)
.ToArray();
var jsonFilePathsFromTopDirectory = _fileSystem.Directory.GetFiles(DirectoryRootPath, searchPattern, searchOption);
Assert.True(addedJsonFilePaths.Length == jsonFilePathsFromTopDirectory.Length);
for (int i = 0; i < addedJsonFilePaths.Length; i++)
{
Assert.Equal(
jsonFilePathsFromTopDirectory[i],
Path.DirectorySeparatorChar + addedJsonFilePaths[i]);
}
}
}
The tests are passing but I would like to know if I could get in trouble when prepending Path.DirectorySeparatorChar
to addedJsonFilePaths[i]
.
The problem is that
jsonFilePathsFromTopDirectory[i]
returns "/config.json"addedJsonFilePaths[i]
returns "config.json"
so I have to prepend a slash at the beginning. Do you have any suggestions how to improve this / avoid later problems?