How To Run Go Tests Sequentially?

Testing is fun

A small trick I wanted to share.

Sometimes, you need to make sure your Go tests are executed sequentially. I did not mention unit tests as one would argue that if unit tests cannot be executed in parallel, these are not unit tests.

Anyway, the first option is to run your tests using go test -p 1.

The second option is the following:

In every test, we have to call defer seq()(). The locking is the first statement executed whereas the unlocking is the last one. This option guarantees that TestFoo and TestBar are executed sequentially regardless of the test option used.