Go 的测试踩坑

2020-10-01 14:27:07 +08:00
 ysmood

一直在用 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

1876 次点击
所在节点    Go 编程语言
2 条回复
pwli
2020-10-01 14:31:32 +08:00
没有看太懂…
ysmood
2020-10-01 14:33:46 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/712078

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX