Skip to main content Inicio Creadores rudironsoni synaxis dotnet-testing-filesystem-testing-abstractions
dotnet-testing-filesystem-testing-abstractions Specialized skill for testing file system operations using System.IO.Abstractions. Use when you need to test File, Directory, Path operations, or simulate file system. Covers IFileSystem, MockFileSystem, file read/write testing, directory operation testing, etc.
Keywords: file testing, filesystem, file testing, file system testing, IFileSystem, MockFileSystem, System.IO.Abstractions, File.ReadAllText, File.WriteAllText, Directory.CreateDirectory, Path.Combine, mock file system, file abstraction
Ir a la instalación Skills Marketplace Descubre y explora habilidades de IA creadas por la comunidad.
Instalar con Codex o Claude Copia este prompt, pégalo en Codex, Claude u otro asistente, y deja que revise la página de la skill y la instale por ti.
Copiar promptMostrar detalles del prompt Un comando directo omite el prompt de revisión. Revisa el origen antes de ejecutarlo.
npx skills add https://github.com/rudironsoni/Synaxis --skill dotnet-testing-filesystem-testing-abstractionsEl comando permanece en una sola línea. Desplázate horizontalmente para revisarlo antes de copiarlo.
¿Prefieres una copia local? Descarga los archivos que SkillsMP tiene disponibles ahora.
Descargar Zip Descargando... Ocupaciones relacionadas SOC
Basado en la clasificación ocupacional SOC
name dotnet-testing-filesystem-testing-abstractions category testing subcategory specialized description Specialized skill for testing file system operations using System.IO.Abstractions. Use when you need to test File, Directory, Path operations, or simulate file system. Covers IFileSystem, MockFileSystem, file read/write testing, directory operation testing, etc.
Keywords: file testing, filesystem, file testing, file system testing, IFileSystem, MockFileSystem, System.IO.Abstractions, File.ReadAllText, File.WriteAllText, Directory.CreateDirectory, Path.Combine, mock file system, file abstraction
targets ["*"] license MIT metadata {"author":"Kevin Tseng","version":"1.0.0","tags":".NET, testing, IFileSystem, MockFileSystem, file testing","related_skills":"nsubstitute-mocking, unit-test-fundamentals, datetime-testing-timeprovider"} claudecode {} opencode {} codexcli {"short-description":".NET skill guidance for dotnet-testing-filesystem-testing-abstractions"} copilot {} geminicli {} antigravity {}
Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.
File System Testing: Using System.IO.Abstractions to Simulate File Operations
Applicable Scenarios
Use this skill when asked to perform the following tasks:
Refactor code directly using System.IO.File, System.IO.Directory and other static classes
Write unit tests for code involving file read/write, directory operations
Use MockFileSystem to simulate various file system states
Test exception scenarios like insufficient file permissions, file not found
Design testable file processing service architecture
Core Principles
1. Fundamental Problem of File System Dependencies
Traditional code directly using System.IO static classes is difficult to test, reasons include:
Speed Issues : Actual disk IO is 10-100x slower than memory operations
Environment Dependency : Test results affected by file system state, permissions, paths
Side Effects : Tests leave traces on disk, affecting other tests
Concurrency Issues : Multiple tests operating on same file create race conditions
Error Simulation Difficulty : Difficult to simulate insufficient permissions, insufficient disk space, etc.
2. System.IO.Abstractions Solution
This is a package that wraps System.IO static classes into interfaces, supporting dependency injection and test doubles.
Core Interface Architecture :
public interface IFileSystem
{
IFile File { get ; }
IDirectory Directory { get ; }
IFileInfo FileInfo { get ; }
IDirectoryInfo DirectoryInfo { get ; }
IPath Path { get ; }
IDriveInfo DriveInfo { get ; }
}
```text
**Required NuGet Packages**:
```xml
<!-- Production environment -->
<PackageReference Include="System.IO.Abstractions" Version="21.*" />
<!-- Test project -->
<PackageReference Include="System.IO.Abstractions.TestingHelpers" Version="21.*" />
```text
**Step **: Change code directly classes to depend `IFileSystem`
```csharp
{
{
File.ReadAllText(path);
}
}
{
IFileSystem _fileSystem;
{
_fileSystem = fileSystem;
}
{
_fileSystem.File.ReadAllText(path);
}
}
```text
**Step **: Register real implementation DI container
```csharp
services.AddSingleton<IFileSystem, FileSystem>();
services.AddScoped<ConfigService>();
```text
**Step **: Use MockFileSystem tests
```csharp
mockFs = MockFileSystem( Dictionary< , MockFileData>
{
[ ] = MockFileData( )
});
service = ConfigService(mockFs);
```text
```csharp
[ ]
{
mockFileSystem = MockFileSystem( Dictionary< , MockFileData>
{
[ ] = MockFileData( ),
[ ] = MockFileData( ),
[ ] = MockDirectoryData()
});
service = ConfigService(mockFileSystem);
result = service.LoadConfigAsync( );
result.Should().Contain( );
}
```text
```csharp
[ ]
{
mockFileSystem = MockFileSystem();
service = ConfigService(mockFileSystem);
service.SaveConfigAsync( , );
mockFileSystem.File.Exists( ).Should().BeTrue();
content = mockFileSystem.File.ReadAllTextAsync( );
content.Should().Contain( );
}
```text
```csharp
[ ]
{
mockFileSystem = MockFileSystem( Dictionary< , MockFileData>
{
[ ] = MockFileData( )
});
service = FileManagerService(mockFileSystem);
service.CopyFileToDirectory( , );
mockFileSystem.Directory.Exists( ).Should().BeTrue();
mockFileSystem.File.Exists( ).Should().BeTrue();
}
```text
When needing to simulate specific exceptions, MockFileSystem has limited support, can use NSubstitute:
```csharp
[ ]
{
mockFileSystem = Substitute.For<IFileSystem>();
mockFile = Substitute.For<IFile>();
mockFileSystem.File.Returns(mockFile);
mockFile.Exists( ).Returns( );
mockFile.ReadAllText( )
.Throws( UnauthorizedAccessException( ));
service = FilePermissionService(mockFileSystem);
result = service.TryReadFile( , content);
result.Should().BeFalse();
content.Should().BeNull();
}
```text
```csharp
[ ]
{
content = ;
mockFileSystem = MockFileSystem( Dictionary< , MockFileData>
{
[ ] = MockFileData(content)
});
processor = StreamProcessorService(mockFileSystem);
result = processor.CountLinesAsync( );
result.Should().Be( );
}
```text
```csharp
[ ]
{
content = ;
mockFileSystem = MockFileSystem( Dictionary< , MockFileData>
{
[ ] = MockFileData(content)
});
service = FileManagerService(mockFileSystem);
info = service.GetFileInfo( );
info.Should().NotBeNull();
info!.Name.Should().Be( );
info.Size.Should().Be(content.Length);
}
```text
```csharp
[ ]
{
mockFileSystem = MockFileSystem( Dictionary< , MockFileData>
{
[ ] = MockFileData( )
});
service = FileManagerService(mockFileSystem);
backupPath = service.BackupFile( );
backupPath.Should().StartWith( );
backupPath.Should().EndWith( );
mockFileSystem.File.Exists(backupPath).Should().BeTrue();
}
```text
**Use Path.Combine to handle paths**:
```csharp
path = _fileSystem.Path.Combine( , );
```text
**Defensively check existence**:
```
{
defaultValue;
}
```text
**Auto-create necessary directories**:
```csharp
dir = _fileSystem.Path.GetDirectoryName(filePath);
(! .IsNullOrEmpty(dir) && !_fileSystem.Directory.Exists(dir))
{
_fileSystem.Directory.CreateDirectory(dir);
}
```text
**Properly handle various IO exceptions**:
```csharp
{
_fileSystem.File.ReadAllTextAsync(path);
}
(UnauthorizedAccessException) { }
(IOException) { }
(DirectoryNotFoundException) { }
```text
**Use independent MockFileSystem each test**:
```csharp
{
[ ]
{
mockFs = MockFileSystem();
}
[ ]
{
mockFs = MockFileSystem();
}
}
```text
**Hardcode path separators**:
```csharp
path = ;
path = ;
path = _fileSystem.Path.Combine( , );
```text
**Use real system unit tests**:
```csharp
realFs = FileSystem();
mockFs = MockFileSystem();
```text
**Ignore exception handling**:
```csharp
content = _fileSystem.File.ReadAllText(path);
(_fileSystem.File.Exists(path))
{
{ _fileSystem.File.ReadAllText(path); }
(IOException) { defaultValue; }
}
```text
- **Speed**: x faster than real operations
- **Reliability**: Not affected disk state
- **Isolation**: Complete isolation between tests
- **Error Simulation**: Can precisely simulate various exception scenarios
- Only create files necessary testing
- Avoid simulating oversized files tests
- For large processing logic, use moderately sized test data:
```csharp
testContent = .Join( ,
Enumerable.Range( , ).Select(i => ));
mockFileSystem.AddFile( , MockFileData(testContent));
```text
See `templates/configmanager-service.cs` complete implementation, including:
- Configuration load save
- JSON serialization deserialization
- Auto-create directories
- Configuration backup functionality
See `templates/filemanager-service.cs` implementation, including:
- File copy backup
- Directory operations
- File information query
- Error handling patterns
This skill content distilled the article series:
- **Day - File IO Testing: Using System.IO.Abstractions to Simulate File System**
- Article: https:
- Sample Code: https:
- [System.IO.Abstractions GitHub](https:
- [System.IO.Abstractions NuGet](https:
- [TestingHelpers NuGet](https:
- `nsubstitute-mocking` - Test doubles mocking
- `unit-test-fundamentals` - Unit testing basics
### 3. Refactoring Steps
1
using
static
on
public
class
ConfigService
public string LoadConfig (string path )
return
public
class
ConfigService
private
readonly
public ConfigService (IFileSystem fileSystem )
public string LoadConfig (string path )
return
2
in
3
in
var
new
new
string
"config.json"
new
"{ \"key\": \"value\" }"
var
new
## MockFileSystem Testing Patterns
### Pattern 1: Default File State
Fact
public async Task LoadConfig_File_Exists_Should_Return_Content ()
var
new
new
string
"config.json"
new
"{ \"key\": \"value\" }"
@"C:\data\users.csv"
new
"Name,Age\nJohn,25"
@"C:\logs\"
new
var
new
var
await
"config.json"
"key"
### Pattern 2: Verify Write Results
Fact
public async Task SaveConfig_Specified_Content_Should_Write_Correctly ()
var
new
var
new
await
"output.json"
"{ \"saved\": true }"
"output.json"
var
await
"output.json"
"saved"
### Pattern 3: Test Directory Operations
Fact
public void CopyFile_Target_Directory_Not_Exists_Should_Auto_Create ()
var
new
new
string
@"C:\source\file.txt"
new
"content"
var
new
@"C:\source\file.txt"
@"C:\target\subfolder"
@"C:\target\subfolder"
@"C:\target\subfolder\file.txt"
### Pattern 4: Use NSubstitute to Simulate Errors
Fact
public void TryReadFile_Insufficient_Permissions_Should_Return_False ()
var
var
"protected.txt"
true
"protected.txt"
new
"Access denied"
var
new
var
"protected.txt"
out
var
## Advanced Testing Techniques
### Stream Operation Testing
Fact
public async Task CountLines_Multi_Line_File_Should_Return_Correct_Count ()
var
"Line 1\nLine 2\nLine 3\nLine 4"
var
new
new
string
"data.txt"
new
var
new
var
await
"data.txt"
4
### File Information Testing
Fact
public void GetFileInfo_File_Exists_Should_Return_Correct_Info ()
var
"Hello, World!"
var
new
new
string
@"C:\test.txt"
new
var
new
var
@"C:\test.txt"
"test.txt"
### Backup File Testing
Fact
public void BackupFile_File_Exists_Should_Create_Timestamp_Backup ()
var
new
new
string
@"C:\data\important.txt"
new
"important data"
var
new
var
@"C:\data\important.txt"
@"C:\data\important_"
".txt"
## Best Practices
### ✅ Should Do
1.
var
"configs"
"app.json"
2.
file
csharp
if (!_fileSystem.File.Exists(filePath ))
return
3.
var
if
string
4.
try
return
await
catch
catch
catch
5.
for
public
class
ServiceTests
Fact
public void Test1 ()
var
new
Fact
public void Test2 ()
var
new
### ❌ Should Avoid
1.
var
"configs\\app.json"
var
"configs/app.json"
var
"configs"
"app.json"
2.
file
in
var
new
var
new
3.
var
if
try
return
catch
return
## Performance Considerations
### MockFileSystem Advantages
10
-100
file
by
### Memory Usage Recommendations
for
in
file
var
string
"\n"
1
1000
$"Line {i} "
"test.txt"
new
## Practical Integration Examples
### Configuration File Management Service
for
file
and
and
file
### File Management Service
for
and
## Reference Resources
### Original Articles
is
from
"Old School Software Engineer's Testing Practice - 30 Day Challenge"
17
and
### Official Documentation
### Related Skills
and