Go 的测试踩坑
資深大佬 : ysmood 0
一直在用 testify 写测试,它算是所有测试库里面比较简单可依赖的。然而它还是有些多年没解决的问题。比如比较时间的大小( v2 才支持了,还在开发中)。
比如下面的代码,看上去很正常,但是其实会触发 testify 的 bug:
import ( "testing" "github.com/stretchr/testify/suite" ) func Test(t *testing.T) { suite.Run(t, &Suite{}) } type Suite struct { suite.Suite } func (s *Suite) TestA() { s.T().Parallel() s.Equal(2, 1) } func (s *Suite) TestB() { s.T().Parallel() }
具体的讨论可以看这里: https://github.com/stretchr/testify/issues/187
testify 之所以有这个问题,核心原因是它的设计会导致 Suite 在多个子测试中被竞争。 为了处理这个问题写了个轻量的库,无任何依赖可以用来替代 testify 的 suite,配合 testify 的 assert 的用法如下:
import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/ysmood/got" ) func Test(t *testing.T) { got.Each(t, beforeEach) } func beforeEach(t *testing.T) Suite { t.Parallel() return Suite{assert.New(t)} } type Suite struct { // struct that holds subtests *assert.Assertions } func (s Suite) A() { // test case A time.Sleep(time.Second) s.Equal(1, 1) } func (s Suite) B() { // test case B time.Sleep(time.Second) s.Equal(2, 1) }
也可以独立使用,用来做一些简单的测试应该会很顺手,不需要写一堆 Test 前缀和 t *testing.T 了:
import ( "testing" "github.com/ysmood/got" ) func Test(t *testing.T) { got.Each(t, S{}) } type S struct { got.Assertion } func (s S) A() { s.Eq(1, 1) } func (s S) B() { s.Gt(2, 1) }
项目地址: https://github.com/ysmood/got
大佬有話說 (2)