如何在 golang 中使用 stretchr/testify 通过 table 测试 运行 证明 setup/teardown?

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

我正在使用 testify for testing. I've set up a suite 进行测试。但是,在使用 table 测试时,我在使用设置和拆卸功能时遇到了问题。这是设计使然吗?

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))
}

当我 运行 TestUnitTestSuite 我得到以下输出:

=== 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

请注意 setupbefore test 在输出中只出现一次,即使有两个测试是 运行。

有没有办法让我在每次 table 测试之前自动 运行 SetupTest(或其他替代方法)?

这是 testify 工作方式的预期行为。 Setup/Before/After 是为 TestSuite 而不是每个子测试(table 测试用例)调用的。有个Github issue here.

您可以在进行实际测试之前在循环中调用 s.SetupTest()