金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks
# 试用 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)
```

posted on 2020-03-13 12:07 金庆 阅读(653) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理