返回

.NET C# 单元测试 mock File.Exists的返回值

2025-02-27 .NET C# 单元测试 220 0

在 .NET 单元测试中,使用 Moq 来模拟 File.Exists 方法的返回值,可以这样做:

1. 使用 Mock<FileSystem>(推荐)

.NET 提供了 System.IO.Abstractions 库,你可以使用 Mock<IFileSystem> 来替代 File,这样更符合依赖注入原则:

using System.IO.Abstractions;
using Moq;
using Xunit;

public class FileServiceTests
{
    [Fact]
    public void Test_FileExists_ReturnsTrue()
    {
        // 创建 Mock 对象
        var mockFileSystem = new Mock<IFileSystem>();
        
        // 设置 File.Exists 返回 true
        mockFileSystem.Setup(fs => fs.File.Exists("test.txt")).Returns(true);

        // 测试
        bool exists = mockFileSystem.Object.File.Exists("test.txt");

        // 断言
        Assert.True(exists);
    }
}

2. 使用 File 直接替换(非推荐)

如果你不能使用 System.IO.Abstractions,可以使用 Shims(需要 Microsoft Fakes 框架)或者 抽象封装 File 访问逻辑:

方法 1:抽象封装

public interface IFileWrapper
{
    bool Exists(string path);
}

public class FileWrapper : IFileWrapper
{
    public bool Exists(string path) => File.Exists(path);
}

// 在单元测试中
var mockFileWrapper = new Mock<IFileWrapper>();
mockFileWrapper.Setup(f => f.Exists("test.txt")).Returns(true);

方法 2:使用 Shims(仅适用于 Visual Studio Enterprise) csharp Copy Edit

using Microsoft.QualityTools.Testing.Fakes;

using (ShimsContext.Create())
{
    System.IO.Fakes.ShimFile.ExistsString = path => true;
    Assert.True(File.Exists("test.txt"));
}

System.IO.Abstractions 是更现代、更推荐的方法。

您可能感兴趣:

阿里云 云服务器 99元1年 2核2G 3M固定带宽 续费与新购同价

DOVE 网络加速器 梯子 免费 试用

椤堕儴