通常介绍一件事,先从基本的开始,然后中级,然后高级篇。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 库的用法。
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
https://godoc.org/github.com/stretchr/testify/assert