Does go test run unit tests concurrently?


When go test is ran it runs your files ending in _test.go by running the functions that start in the format TestXxx and use the (*t testing.T) module. I was wondering if each function in the _test.go file were ran concurrently or if it definitively ran each function separately? Does it create a go routine for each one? If it does create a go routine for each one, can I monitor the go routines in some way? Is it ever possible to do something like golibrary.GoRoutines() and get an instance for each one and monitor them some how or something like that?

Note: this question assumes you using the testing framework that comes with go (testing).


Yes, tests are executed as goroutines and, thus, executed concurrently.

However, tests do not run in parallel by default as pointed out by @jacobsa. To enable parallel execution you would have to call t.Parallel() in your test case and set GOMAXPROCS appropriately or supply -parallel N (which is set to GOMAXPROCS by default).

The simplest solution for your case when running tests in parallel would be to have a global slice for port numbers and a global atomically incremented index that serves as association between test and port from the slice. That way you control the port numbers and have one port for each test. Example:

import "sync/atomic"

var ports [...]uint64 = {10, 5, 55}
var portIndex uint32

func nextPort() uint32 {
    return atomic.AddUint32(&portIndex, 1)

Answered By – nemo

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.