notexOPENOverview
Notex/Languages/Running Tests Concurrently
05.15LESSON 15 OF 29 · 2 MIN READ

Running Tests Concurrently

Always free to read

By default, unit tests are run sequentially. Since each unit test is supposed to be independent from every other unit test, they make ideal candidates for concurrency. To make a unit test run concurrently with other tests, call the Parallel method on *testing.T as the first line in your test:

func TestMyCode(t *testing.T) {
    t.Parallel()
    // rest of test goes here
}

Parallel tests run concurrently with other tests marked as parallel. The Go runtime manages this for you automatically; there’s no exposed configuration.

You can also call Parallel from within a table test:

func TestParallelTable(t *testing.T) {
    data := []struct {
        name   string
        input  int
        output int
    }{
        {"a", 10, 20},
        {"b", 30, 40},
        {"c", 50, 60},
    }
    for _, d := range data {
        t.Run(d.name, func(t *testing.T) {
            t.Parallel()
            t.Log(d.input, d.output)
            out := toTest(d.input)
            if out != d.output {
                t.Error("didn't match", out, d.output)
            }
        })
    }
}

The table test subtests run in parallel with each other, but the parent test blocks until all of the subtests complete.

You can run this code on The Go Playground.

The advantage of parallel tests is they can speed up long-running test suites. There are some disadvantages, though. If you have multiple tests that rely on the same shared mutable state, do not mark them as parallel, because you will get inconsistent results. (But after all of my warnings, you don’t have any shared mutable state in your application, right?) Also be aware that your test will panic if you mark it as parallel and use the Setenv method in your test function.

Note

Go 1.22 (released in February, 2024) changed the lifecycle of the index and value variables in for loops. The compiler now creates a new copy of the index and value variables on each iteration if there’s any chance they could be captured by a closure. This eliminated bugs in parallel tests that were using shared index and value state. If you are still using Go 1.21 or earlier (or have the Go version in the go directive in your go.mod file set to 1.2.1 or earlier), I strongly recommend upgrading to take advantage of this improved behavior.

Now that you have a way to run lots of tests, you’ll learn about code coverage to find out what your tests are testing.

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K