Go Subtests and Sub-benchmarks

Image for post
Image for post

Go uses a very simple approach to everything. This also includes the testing package that ships with Go. The lack of assertions often drives people to use another testing framework like testify.

Go 1.7 introduced subtest and sub-benchmarks. I haven’t seen much written on this yet… So here is a quick run down.

Subtests are exactly what they sound like, it’s running a test inside another test:

func TestFoo(t *testing.T) {
// <setup code>
t.Run("A=1", func(t *testing.T) { ... })
t.Run("A=2", func(t *testing.T) { ... })
t.Run("B=1", func(t *testing.T) { ... })
// <tear-down code>

This is useful for grouping or sharing tests that need to use the same data fixtures.

Since each individual subtests get their own test name (as if it was independent) you can use this for filtering on the command line:

go test -run Foo     # Run top-level tests matching "Foo".
go test -run Foo/A= # Run subtests of Foo matching "A=".
go test -run /A=1 # Run all subtests of a top-level test matching "A=1”.

Parallel Tests

The existing testingpackage does have support for running tests in parallel, usually for benchmarks. However, I have not seen it used that much. Perhaps because it is difficult or messy to manage them.

Subtests greatly simplify by both locally grouping the tests and intrinsically running them in parallel and only moving on once all the subtests have finished:

func TestTeardownParallel(t *testing.T) {
// t.Run() will not return until the parallel tests finish.
t.Run("group", func(t *testing.T) {
t.Run("Test1", parallelTest1)
t.Run("Test2", parallelTest2)
t.Run("Test3", parallelTest3)
// <tear-down code>

Originally published at http://elliot.land on June 18, 2016.

Written by

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓 elliotchance@gmail.com

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