typestar

Parallel subtests in Go

t.Parallel pauses a subtest until the others have started, then runs them together.

func Double(n int) int { return n * 2 }

func TestDoubleParallel(t *testing.T) {
    cases := []struct {
        name string
        in   int
        want int
    }{
        {"one", 1, 2},
        {"two", 2, 4},
        {"three", 3, 6},
    }

    for _, c := range cases {
        t.Run(c.name, func(t *testing.T) {
            t.Parallel()
            if got := Double(c.in); got != c.want {
                t.Errorf("Double(%d) = %d, want %d", c.in, got, c.want)
            }
        })
    }
}

How it works

  1. Every parallel subtest must be independent.
  2. The parent finishes only when its parallel children do.
  3. Shared state needs a lock, or the -race flag will say so.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
362
Tokens
129
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.

Type this snippet

Step 1 of 2 in Running them, step 11 of 13 in Testing.

← Previous Next →