The testing/fstest package provides utilities to create in-memory file systems for testing code that interacts with the io/fs interface. Use fstest.MapFS to define a virtual file system with specific content and pass it to your code instead of the real disk.
package main
import (
"io/fs"
"testing"
"testing/fstest"
)
func TestMyReader(t *testing.T) {
// Create a virtual file system with test data
fs := fstest.MapFS{
"data.txt": &fstest.MapFile{
Data: []byte("hello world"),
},
}
// Pass the virtual FS to the function under test
// Example: content, err := ReadFile(fs, "data.txt")
if _, err := fs.Open("data.txt"); err != nil {
t.Fatalf("failed to open file: %v", err)
}
// Verify behavior without touching the real disk
info, err := fs.Stat("data.txt")
if err != nil {
t.Fatalf("failed to stat file: %v", err)
}
if info.Size() != 11 {
t.Errorf("expected size 11, got %d", info.Size())
}
}