我正在编写一个单元测试来检查对文件进行操作的一些方法。我在库端使用了 System.IO.Abstraction,在 UnitTests 端使用了 System.IO.Abstraction.UnitTesting。
我使用的是 MacOS,但我也希望能够在 Windows 上运行测试。问题出在路径上,因为我们知道在 Windows 上它就像“C:\MyDir\MyFile.pdf”,但对于 Linux/MacOS,它更像是“/c/MyDir/MyFile.pdf”。
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ @"/c/scans/myfile.pdf", new MockFileData("Some text") },
{ @"/c/scans/mysecondfile.pdf", new MockFileData("Some text") },
{ @"/c/scans/mydog.jpg", new MockFileData("Some text") }
});
var fileService = new FileService(fileSystem);
var scanDirPath = @"/c/scans/";
我不知道该如何处理这件事。我想知道如何根据平台在 xunit 测试的构造函数中设置“初始”路径,但我不确定这是否是一个好的做法。
我遇到了同样的场景,我需要在 Windows 和 Linux 上使用
System.IO.Abstraction.TestingHelpers
的 MockFileSystem
执行单元测试。我通过添加平台检查然后使用该平台的预期字符串格式使其工作。
遵循相同的逻辑,您的测试可能如下所示:
[Theory]
[InlineData(@"c:\scans\myfile.pdf", @"/c/scans/myfile.pdf")]
[InlineData(@"c:\scans\mysecondfile.pdf", @"/c/scans/mysecondfile.pdf")]
[InlineData(@"c:\scans\mydog.jpg", @"/c/scans/mydog.jpg")]
public void TestName(string windowsFilepath, string macFilepath)
{
// Requires a using statement for System.Runtime.InteropServices;
bool isExecutingOnWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
bool isExecutingOnMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
MockFileSystem fileSystem;
if (isExecutingOnWindows)
{
fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ windowsFilepath, new MockFileData("Some text") }
};
}
else if (isExecutingOnMacOS)
{
fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ macFilepath, new MockFileData("Some text") }
};
}
else
{
// Throw an exception or handle this however you choose
}
var fileService = new FileService(fileSystem);
// Test logic...
}
System.IO.Abstractions.TestingHelpers 包为此目的提供了一个
MockUnixSupport
类。
这是推荐用法(来自
TestableIO.System.IO.Abstractions.TestingHelpers
自己的测试):
using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport;
var path = XFS.Path(@"c:\something\demo.txt");
您的示例代码如下:
using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport;
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ XFS.Path(@"c:\scans\myfile.pdf"), new MockFileData("Some text") },
{ XFS.Path(@"c:\scans\mysecondfile.pdf"), new MockFileData("Some text") },
{ XFS.Path(@"c:\scans\mydog.jpg"), new MockFileData("Some text") }
});
var fileService = new FileService(fileSystem);
var scanDirPath = XFS.Path(@"c:\scans\");
然后您就可以编写测试而无需任何条件代码。