Apr 12, 2020 · 1 minute

📋 Building Go Test Suites using Testify

While testing itself is a first-class citizen in Go, features like nested tests and setup and teardown mechanisms are not. Luckily, libraries like testify add capabilities for writing powerful assertions, mocking, and organizing tests in suites.

import (
"testing"
"github.com/stretchr/testify/suite"
)
// We'll be able to store suite-wide
// variables and add methods to this
// test suite struct
type ExampleTestSuite struct {
suite.Suite
}
// This is an example test that will always succeed
func (suite *ExampleTestSuite) TestExample() {
suite.Equal(true, true)
}
// We need this function to kick off the test suite, otherwise
// "go test" won't know about our tests
func TestExampleTestSuite(t *testing.T) {
suite.Run(t, new(ExampleTestSuite))
}

The code above will create and register an example test suite that can be run by starting go test:

$ go test ./...

But that's not all there is to it! We can define lifecycle functions like SetupSuite, SetupTest, BeforeTest, and AfterTest to run custom setup and teardown code in between tests or before the suite starts. From the docs, I've added some empty hooks you can use:

// This will run right before the test starts
// and receives the suite and test names as input
func (suite *ExampleTestSuite) BeforeTest(suiteName, testName string) {}
// This will run after test finishes
// and receives the suite and test names as input
func (suite *ExampleTestSuite) AfterTest(suiteName, testName string) {}
// This will run before before the tests in the suite are run
func (suite *ExampleTestSuite) SetupSuite() {}
// This will run before each test in the suite
func (suite *ExampleTestSuite) SetupTest() {}

As you can see, with testify, it's really straightforward to build test suites the way you'd imagine them to work!


Thanks for reading this short guide! If you've got any questions, suggestions, or feedback in general, don't hesitate to reach out on Twitter or by mail.