go / intermediate
Snippet
Writing Parallel Table-Driven Tests in Go
Table-driven tests in Go isolate test inputs and expected outputs in a clean structure. Adding t.Parallel() inside the dynamically running t.Run subtests allows Go's test runner to execute them concurrently, optimizing execution speed.
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
package mainimport "testing"func CalculateDiscount(price int) int {if price > 100 {return price - 20}return price}func TestCalculateDiscount(t *testing.T) {tests := []struct {name stringinput intexpected int}{{"No discount for low price", 50, 50},{"Apply discount for high price", 150, 130},}for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {t.Parallel()got := CalculateDiscount(tc.input)if got != tc.expected {t.Errorf("got %d, want %d", got, tc.expected)}})}}
Breakdown
1
tests := []struct {
Defines a slice of anonymous structs representing the test cases.
2
t.Run(tc.name, func(t *testing.T) {
Executes a subtest for each test case dynamically naming it.
3
t.Parallel()
Signals that this subtest can run concurrently with other parallel tests.