go test 常见套路(3)

2019-09-20 08:52:10 +08:00
 guonaihong

通常介绍一件事,先从基本的开始,然后中级,然后高级篇。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)
    }

}

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

=== 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 库文档

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

我的 github

https://github.com/guonaihong/gout

1198 次点击
所在节点    程序员
0 条回复

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

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

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

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

© 2021 V2EX