Run parallel tests with isolation
Run parallel tests with isolation
Calling t.Parallel permits a test to run concurrently with other parallel tests. Each parallel subtest pauses until its parent test function returns (or its immediate sequential parent group finishes its function). Use independent fixtures, not a shared file, mutable global or process-wide environment variable. Limit concurrency with go test -parallel=2 and test order dependence with -shuffle=on -count=3.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "os" "path/filepath" "testing")
func TestLesson(t *testing.T) { for _, value := range []string{"alpha", "beta"} { value := value t.Run(value, func(t *testing.T) { t.Parallel() path := filepath.Join(t.TempDir(), "record.txt") if err := os.WriteFile(path, []byte(value), 0600); err != nil { t.Fatal(err) } got, err := os.ReadFile(path) if err != nil || string(got) != value { t.Fatal(string(got), err) } }) }}Each subtest gets its own directory, so identical file names do not collide. TempDir registers automatic cleanup. The explicit value copy also works with older loop-variable semantics. Do not use t.Setenv in a parallel test or a test with a parallel ancestor: environment variables belong to the whole process.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonJoin a group before checking shared results
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "sync" "testing")
func TestLesson(t *testing.T) { var mu sync.Mutex sum := 0 t.Run("group", func(t *testing.T) { for _, n := range []int{1, 2, 3} { n := n t.Run(string(rune('a'+n)), func(t *testing.T) { t.Parallel(); mu.Lock(); sum += n; mu.Unlock() }) } }) if sum != 6 { t.Fatal(sum) }}The outer sequential group does not return to its caller until the parallel descendants finish. The mutex protects concurrent updates; the final assertion runs after completion. Prefer isolated state over locks when possible. defer in a parent function can run before parallel children resume; use t.Cleanup for a resource they still need.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Run two parallel HTTP handler subtests with a separate recorder per case; test status 200 for /ok and 404 for /missing. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced testing 05: Run parallel tests with isolation
Check the lesson objective before moving on.
Why avoid t.Setenv in parallel tests?
When should cleanup of a shared parent fixture run?