试用 go test suite

试用 go test suite

(金庆的专栏 2020.3)

github.com/stretchr/testify/suite 提供了测试套件功能,
可以在整个套件开始结束时执行动作,也可以在每个测试开始结束时执行动作。

假设有以下2个函数需要测试:

func foo() {
	fmt.Printf("foo...\n")
}

func goo() {
	fmt.Printf("goo...\n")
}

建立如下测试文件:


import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/suite"
)

type _Suite struct {
	suite.Suite
}

func (s *_Suite) AfterTest(suiteName, testName string) {
	fmt.Printf("AfterTest: suiteName=%s, testName=%s\n", suiteName, testName)
}

func (s *_Suite) BeforeTest(suiteName, testName string) {
	fmt.Printf("BeforeTest: suiteName=%s, testName=%s\n", suiteName, testName)
}

func (s *_Suite) SetupSuite() {
	fmt.Printf("SetupSuite()...\n")
}

func (s *_Suite) TearDownSuite() {
	fmt.Printf("TearDownSuite()...\n")
}

func (s *_Suite) SetupTest() {
	fmt.Printf("SetupTest()...\n")
}

func (s *_Suite) TearDownTest() {
	fmt.Printf("TearDownTest()...\n")
}

func (s *_Suite) TestFoo() {
	foo()
}

func (s *_Suite) TestGoo() {
	goo()
}

// 让 go test 执行测试
func TestGooFoo(t *testing.T) {
	suite.Run(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 使用 assert.Assertion 执行断言, 见Suite定义:

type Suite struct {
	*assert.Assertions
	require *require.Assertions
	t       *testing.T
}

可以这样执行多个断言,失败时仍执行其他断言:

func (m *MySuite) TestAdd() {
	m.Equal(1, Add(1, 1)) // FAIL
	m.Equal(0, Add(1, 1)) // FAIL
}

可以重载成使用 require.Assertion,失败时中断执行:

type MySuite struct {
	suite.Suite
	*require.Assertions
}

func (m *MySuite) TestAdd() {
	m.Equal(1, Add(1, 1)) // FAIL and return
	m.Equal(0, Add(1, 1)) // 不执行
}

或者任意指定:

m.Assert().Equal(1, 2)
m.Require().Equal(1, 2)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值