试用 go test suite
(金庆的专栏 2020.3)
/stretchr/testify/suite 提供了测试套件功能,
可以在整个套件开始结束时执行动作,也可以在每个测试开始结束时执行动作。
假设有以下2个函数需要测试:
func foo() {
("foo...\n")
}
func goo() {
("goo...\n")
}
建立如下测试文件:
import (
"fmt"
"testing"
"/stretchr/testify/suite"
)
type _Suite struct {
}
func (s *_Suite) AfterTest(suiteName, testName string) {
("AfterTest: suiteName=%s, testName=%s\n", suiteName, testName)
}
func (s *_Suite) BeforeTest(suiteName, testName string) {
("BeforeTest: suiteName=%s, testName=%s\n", suiteName, testName)
}
func (s *_Suite) SetupSuite() {
("SetupSuite()...\n")
}
func (s *_Suite) TearDownSuite() {
("TearDownSuite()...\n")
}
func (s *_Suite) SetupTest() {
("SetupTest()...\n")
}
func (s *_Suite) TearDownTest() {
("TearDownTest()...\n")
}
func (s *_Suite) TestFoo() {
foo()
}
func (s *_Suite) TestGoo() {
goo()
}
// 让 go test 执行测试
func TestGooFoo(t *) {
(t, new(_Suite))
}
输出如下:
=== RUN TestGooFoo
SetupSuite()...
=== RUN TestGooFoo/TestFoo
SetupTest()...
BeforeTest: suiteName=_Suite, testName=TestFoo
foo...
AfterTest: suiteName=_Suite, testName=TestFoo
TearDownTest()...
=== RUN TestGooFoo/TestGoo
SetupTest()...
BeforeTest: suiteName=_Suite, testName=TestGoo
goo...
AfterTest: suiteName=_Suite, testName=TestGoo
TearDownTest()...
TearDownSuite()...
--- PASS: TestGooFoo (0.00s)
--- PASS: TestGooFoo/TestFoo (0.00s)
--- PASS: TestGooFoo/TestGoo (0.00s)
PASS
SetupSuite()/TearDownSuite() 仅执行一次,
而 SetupTest()/TearDownTest()/BeforeTest()/AfterTest()对套件中的每个测试执行一次。
缺省情况下,Suite 使用 执行断言, 见Suite定义:
type Suite struct {
*
require *
t *
}
可以这样执行多个断言,失败时仍执行其他断言:
func (m *MySuite) TestAdd() {
(1, Add(1, 1)) // FAIL
(0, Add(1, 1)) // FAIL
}
可以重载成使用 ,失败时中断执行:
type MySuite struct {
*
}
func (m *MySuite) TestAdd() {
(1, Add(1, 1)) // FAIL and return
(0, Add(1, 1)) // 不执行
}
或者任意指定:
().Equal(1, 2)
().Equal(1, 2)