A specialized skill for testing file system operations using System.IO.Abstractions. Use this when you need to test File, Directory, Path operations or mock the file system. Covers IFileSystem, MockFileSystem, file read/write testing, directory operation tests, and more. Keywords: file testing, filesystem, file tests, filesystem testing, IFileSystem, MockFileSystem, System.IO.Abstractions, File.ReadAllText, File.WriteAllText, Directory.CreateDirectory, Path.Combine, mock file system, file abstraction
傳統直接使用 System.IO 靜態類別的程式碼難以測試,原因包括:
將 System.IO 靜態類別包裝成介面的套件,支援依賴注入和測試替身。
必要 NuGet 套件:
<!-- 正式環境 -->
<PackageReference Include="System.IO.Abstractions" Version="22.1.0" />
<!-- 測試專案 -->
<PackageReference Include="System.IO.Abstractions.TestingHelpers" Version="22.1.0" />
步驟一:將直接使用靜態類別的程式碼改為依賴 IFileSystem
// ❌ 重構前(不可測試)
public class ConfigService
{
public string LoadConfig(string path) => File.ReadAllText(path);
}
// ✅ 重構後(可測試)
public class ConfigService
{
private readonly IFileSystem _fileSystem;
public ConfigService(IFileSystem fileSystem) => _fileSystem = fileSystem;
public string LoadConfig(string path) => _fileSystem.File.ReadAllText(path);
}
步驟二:在 DI 容器中註冊真實實作
services.AddSingleton<IFileSystem, FileSystem>();
步驟三:在測試中使用 MockFileSystem
var mockFs = new MockFileSystem(new Dictionary<string, MockFileData>
{
["config.json"] = new MockFileData("{ \"key\": \"value\" }")
});
var service = new ConfigService(mockFs);
涵蓋四種核心測試模式:預設檔案狀態建立、驗證寫入結果、目錄操作測試、使用 NSubstitute 模擬 IO 異常(UnauthorizedAccessException 等)。另含進階技巧:串流操作測試、檔案資訊查詢測試、備份檔案測試。
完整 MockFileSystem 測試模式與進階技巧請參考 references/mockfilesystem-patterns.md
_fileSystem.Path.Combine("configs", "app.json")_fileSystem.File.Exists()Path.Combine 取代 \\ 或 /請參考 templates/ 目錄下的完整實作:
configmanager-service.cs - 設定檔管理服務(載入/儲存/備份)filemanager-service.cs - 檔案管理服務(複製/目錄操作/錯誤處理)本技能內容提煉自「老派軟體工程師的測試修練 - 30 天挑戰」系列文章:
nsubstitute-mocking - 測試替身與模擬unit-test-fundamentals - 單元測試基礎npx skills add kevintsengtw/dotnet-测试-文件系统-抽象下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer