Afero: Mocking File Systems for Unit Testing in Go

Jerry An
2 min readJan 20, 2024
Image generated AI

Mocking file systems for testing is crucial for unit testing. This Medium post delves into how to use Afero to abstract file system complexities, making code more portable and testable.

For more details, visit the Afero GitHub repository.

Example

Here’s a simple example of a unit test in Go using Afero for file system operations:

  1. First, install the Afero package:

go get github.com/spf13/afero

2. Create a Go file for your application logic (e.g., main.go):

package main

import (
"github.com/spf13/afero"
)

func WriteToFile(fs afero.Fs, filename string, content string) error {
file, err := fs.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(content)
return err
}

3. Create a test file (e.g., main_test.go):

package main

import (
"testing"
"github.com/spf13/afero"
)

func TestWriteToFile(t *testing.T) {
//…

--

--