【发布时间】:2022-01-19 12:37:14
【问题描述】:
我创建了一个扩展方法,将所有 JSON 配置文件添加到 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;
}
}
并希望使用 xUnit 为其创建测试。基于
How do you mock out the file system in C# for unit testing?
我安装了 System.IO.Abstractions 和 System.IO.Abstractions.TestingHelpers 包并开始测试是否已添加目录中的 JSON 文件
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]);
}
}
}
测试通过了,但我想知道在将Path.DirectorySeparatorChar 附加到addedJsonFilePaths[i] 时是否会遇到麻烦。
问题是
-
jsonFilePathsFromTopDirectory[i]返回“/config.json” -
addedJsonFilePaths[i]返回“config.json”
所以我必须在开头加上一个斜杠。您对如何改进/避免以后出现问题有什么建议吗?
【问题讨论】:
标签: c#