How to run testify setup/teardown with table tests using stretchr/testify in golang?
Asked Answered
S

2

9

I'm using testify for testing. I've set up a suite for my tests. However, I'm having trouble using the set up and tear down features when using table tests. Is this by design?

package workflows

import (
    "testing"

    log "github.com/sirupsen/logrus"
    "github.com/stretchr/testify/suite"
)

type UnitTestSuite struct {
    suite.Suite
}

func (s *UnitTestSuite) SetupTest() {
    log.Info("setup")
}

func (s *UnitTestSuite) BeforeTest(suiteName, testName string) {
    log.Info("before test")
}

func (s *UnitTestSuite) AfterTest(suiteName, testName string) {
    log.Info("After test")
}


func (s *UnitTestSuite) Test_TableTest() {

    type testCase struct {
        name string
    }

    testCases := []testCase{
        {
            name: "1",
        },
        {
            name: "2",
        },
    }

    for _, testCase := range testCases {

        s.Run(testCase.name, func() {
            // logic ...
            // NOTE that the SetupTest and BeforeTest do not get called for each test here
        })
    }
}

func TestUnitTestSuite(t *testing.T) {
    suite.Run(t, new(UnitTestSuite))
}

When I run the TestUnitTestSuite I get the following output:

=== RUN   TestUnitTestSuite
--- PASS: TestUnitTestSuite (0.00s)
=== RUN   TestUnitTestSuite/Test_TableTest
time="2021-04-17T07:49:28-04:00" level=info msg=setup
time="2021-04-17T07:49:28-04:00" level=info msg="before test"
    --- PASS: TestUnitTestSuite/Test_TableTest (0.00s)
=== RUN   TestUnitTestSuite/Test_TableTest/1
        --- PASS: TestUnitTestSuite/Test_TableTest/1 (0.00s)
=== RUN   TestUnitTestSuite/Test_TableTest/2
time="2021-04-17T07:49:28-04:00" level=info msg="After test"
        --- PASS: TestUnitTestSuite/Test_TableTest/2 (0.00s)
PASS

Note that setup and before test appear only once in the output even though there are two tests being run.

Is there a way for me to automatically run SetupTest (or some alternative) prior to each of my table tests?

Sherrie answered 17/4, 2021 at 11:51 Comment(0)
S
7

This is the intended behaviour of how testify works. The Setup/Before/After are called for the TestSuite rather than per subtest (table test case). There is a Github issue here.

You can just call s.SetupTest() within the loop before you do the actual test.

Semitrailer answered 17/4, 2021 at 13:14 Comment(0)
P
0

Testify released in v1.8.2 these interfaces to be implemented and be executed at the SubTest level:

func (s *Suite) SetupSubTest() {
    fmt.Println("start subtest")
}
func (s *Suite) TearDownSubTest() {
    fmt.Println("tear down subtest")
}

In your case, you can use the SetupSubTest() to add you the setup logic to be execute before each table test.

Posada answered 17/5 at 1:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.