go / expert
Snippet
Hermetic Subtest Isolation with Parallel Execution Control and Cleanup Hooks
Parallel testing with subtests requires careful management of closure variable capture, resource cleanup order via t.Cleanup, and helper stack trace preservation with t.Helper(). Utilizing t.Cleanup guarantees teardown even if subtests fail or panic.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package mainimport ("testing")type TestEnv struct {ID string}func SetupEnv(t *testing.T) *TestEnv {t.Helper()env := &TestEnv{ID: t.Name()}t.Cleanup(func() {// Teardown resource after subtest completes})return env}func TestConcurrentWorkflows(t *testing.T) {cases := []struct {name stringinput int}{{"case_alpha", 10},{"case_beta", 20},}for _, tc := range cases {tc := tct.Run(tc.name, func(t *testing.T) {t.Parallel()env := SetupEnv(t)if env.ID == "" {t.Fatalf("expected valid test env ID")}})}}
Breakdown
1
t.Helper()
Marks the function as a test helper so log messages report the caller's source line.
2
t.Cleanup(func() { ... })
Registers a stack-LIFO teardown callback executed automatically when the test finishes.
3
t.Parallel()
Signals that this subtest can be executed concurrently with other parallel tests.