How To Run Go Tests Sequentially?

Image for post
Image for post
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.

Written by

Software Engineer, Go, Rust, Java | 改善

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store