我正在编写一个单元测试来检查对文件进行操作的一些方法。我在库端使用了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测试的构造函数中设置“初始”路径,但我不确定这是否是一个好的做法。
发布于 2021-07-22 03:17:06
我遇到了同样的情况,我需要在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...
}https://stackoverflow.com/questions/66375235
复制相似问题