V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
ysmood
V2EX  ›  Go 编程语言

Go 的测试踩坑

  •  
  •   ysmood ·
    ysmood · 2020-10-01 14:27:07 +08:00 · 1868 次点击
    这是一个创建于 1302 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一直在用 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 条回复    2020-10-01 14:33:46 +08:00
    pwli
        1
    pwli  
       2020-10-01 14:31:32 +08:00 via Android
    没有看太懂…
    ysmood
        2
    ysmood  
    OP
       2020-10-01 14:33:46 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5745 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 06:25 · PVG 14:25 · LAX 23:25 · JFK 02:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.