Using Testify suite setup/teardown to run operations before/after groups of tests in Go

The standard testing library in go lacks setup and teardown features, Testify adds this feature (and many others).

For demonstrative purposes I’ve included some code below, followed by its output.

package data

import (


type MyTestSuite struct {
	db *Store

// listen for 'go test' command --> run test methods
func TestMyTestSuite(t *testing.T) {
	suite.Run(t, new(MyTestSuite))

// run once, before test suite methods
func (s *MyTestSuite) SetupSuite() {

	// connect the database, save to 's.db'

// run once, after test suite methods
func (s *MyTestSuite) TearDownSuite() {

	// delete the created database

// run before each test
func (s *MyTestSuite) SetupTest() {

// run after each test
func (s *MyTestSuite) TearDownTest() {

// run before each test
func (s *MyTestSuite) BeforeTest(suiteName, testName string) {
	log.Println("BeforeTest()", suiteName, testName)

// run after each test
func (s *MyTestSuite) AfterTest(suiteName, testName string) {
	log.Println("AfterTest()", suiteName, testName)

func (s *MyTestSuite) TestExample1() {
	s.Equal(true, true)

func (s *MyTestSuite) TestExample2() {
	s.Equal(true, true)
Code language: Go (go)
% go test -v

=== RUN   TestDataTestSuite
2022/03/10 05:58:57 SetupSuite()

=== RUN   TestDataTestSuite/TestExample1
2022/03/10 05:58:57 SetupTest()
2022/03/10 05:58:57 BeforeTest() MyTestSuite TestExample1
2022/03/10 05:58:57 AfterTest() MyTestSuite TestExample1
2022/03/10 05:58:57 TearDownTest()

=== RUN   TestDataTestSuite/TestExample2
2022/03/10 05:58:57 SetupTest()
2022/03/10 05:58:57 BeforeTest() MyTestSuite TestExample2
2022/03/10 05:58:57 AfterTest() MyTestSuite TestExample2
2022/03/10 05:58:57 TearDownTest()

2022/03/10 05:58:57 TearDownSuite()

--- PASS: TestDataTestSuite (0.00s)
    --- PASS: TestDataTestSuite/TestExample1 (0.00s)
    --- PASS: TestDataTestSuite/TestExample2 (0.00s)
PASSCode language: Bash (bash)

In the above example I’m using SetupSuite to create a test database, and TearDownSuite to deleted it after the suite tests have concluded.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.