跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • Go 的测试踩坑
未分類
6 10 月 2020

Go 的测试踩坑

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)

  • 資深大佬 : pwli

    没有看太懂…

  • 主 資深大佬 : ysmood

    @pwli 具体的讨论看这个 https://github.com/stretchr/testify/issues/187

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具