c# - System.IO.Abstraction.TestingHelpers - 在不同平台上进行测试

标签 c# xunit

我正在编写一个单元测试来检查对文件进行操作的一些方法。我在库端使用了 System.IO.Abstraction,在单元测试端使用了 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.TestingHelpersMockFileSystem 执行单元测试。我通过为平台添加检查然后使用该平台的预期字符串格式来使其正常工作。

按照相同的逻辑,您的测试可能如下所示:

[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...
}

关于c# - System.IO.Abstraction.TestingHelpers - 在不同平台上进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66375235/

相关文章:

c# - 如何在 Win8.1x64 中配置 EmguCV 和 Visual Studio Express 2010

c# - XNA 中是否有 3D 等效项?

c# - 序列化和反序列化的 NullValueHandling 的不同值

c# - ASP NET MVC RAZOR 上传多个图像文件列表

c# - 使用 xUnit 引用作为 NuGet 包部署项目

c# - 如何在您的应用程序中找到递归?

xunit - 使用具有 NSubstitute 自动数据属性的 AutoFixture 时测试丢失

hudson - 在Hudson CI中为CUnit配置xUnit

c# - 带静态值的单元测试

c# - xUnit 非静态成员数据