V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
guonaihong
V2EX  ›  程序员

go test 常见套路(3)

  •  
  •   guonaihong ·
    guonaihong · 2019-09-20 08:52:10 +08:00 · 1196 次点击
    这是一个创建于 1681 天前的主题,其中的信息可能已经有所发展或是发生改变。

    通常介绍一件事,先从基本的开始,然后中级,然后高级篇。go test(3)高级篇准备的是如何更快,更爽的写 test 代码。

    先来一段不开挂的写法

    package test
    
    import (
        "testing"
    )
    
    func TestSomething(t *testing.T) {
    
        var a string = "Hello"
        var b string = "Hellox"
    
        // 传统方式
        if a != b { 
            t.Errorf("got %s want %s, The two words should be the same.\n", a, b)
        }   
    
    }
    
    

    你会发现模板化的错误日志是很花时间的,这可能就导致一些童鞋不愿意写 test code。 有没有更爽的写法,还真有。下面是某个 test 库的用法。

    引入 testify 库

    • 使用库的写法
    package test
    
    import (
        "github.com/stretchr/testify/assert"
        "testing"
    )
    
    func TestSomething(t *testing.T) {
    
        var a string = "Hello"
        var b string = "Hellox"
    
        // 使用 assert 库的代码
        assert.Equal(t, a, b)
    
        // 如果用传统方式
        if a != b {
            t.Errorf("got %s want %s, The two words should be the same.\n", a, b)
        }
    
    }
    
    

    一对比就知道撸的代码变少了。

    • 输出对比 assert 库更有个贴心的错误 diff 日志,就像 git diff 一样爽
    === RUN   TestSomething
    --- FAIL: TestSomething (0.00s)
        test_test.go:13:
                Error Trace:    test_test.go:13
                Error:          Not equal:
                                expected: "Hello"
                                actual  : "Hellox"
    
                                Diff:
                                --- Expected
                                +++ Actual
                                @@ -1 +1 @@
                                -Hello
                                +Hellox
                Test:           TestSomething
        test_test.go:16: got Hello want Hellox, The two words should be the same. //这里是用标准库输出
    FAIL
    FAIL    test    0.002s
    
    

    更多常见用法

    • assert.NoError(t, err)。如果 err 不为 nil 会打印错误
    • assert.NotEqual(t, obj1, obj2) 不相等打印错误
    • assert.NotNil(t, err)为空指针打印错误
    • assert.Nil(t, err)不为空指针打印错误

    assert 库文档

    https://godoc.org/github.com/stretchr/testify/assert

    我的 github

    https://github.com/guonaihong/gout

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2691 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:22 · PVG 10:22 · LAX 19:22 · JFK 22:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.