How To Run Go Tests Sequentially?

Teiva Harsanyi
Nov 13, 2019 · 1 min read
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.

Teiva Harsanyi

Written by

Software Engineer, Go & Java. Clean Coder, FP, Mechanical Sympathiser, Distributed Systems, DDD. 🇫🇷 in 🇬🇧. 改善

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade