Golang Unit Test for Beginners
我一直覺得寫測試是程式開發中相當重要的一環,不論對自己、對他人都有相當的益處。今天來說說 golang 要怎麼寫 unit test,如果你是 golang 老手,就可以左轉了 XD
Package
golang 提供一個很方便的 package - testing
。但其實除了 test 以外,它還能做 benchmark,這部分有機會再寫一篇文章專門介紹。
Demo
這邊用個簡單的 sum
來 demo,此為 foo.go
檔案
package foo
// Sum, to add all nums
func Sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}
golang 中測試檔案會用 {file}_test.go
這種 pattern 來表示,因此這個 demo 對應的就是 foo_test.go
package foo
import "testing"
func TestSum(t *testing.T) {
a := 1
b := 2
c := 3
expected := a + b + c
actual := Sum(a, b, c)
if expected != actual {
t.Errorf("Expected %d got %d", expected, actual)
}
}
用很簡單的 expected vs acutal 的方式來測試該 function
Run test
usage: go test [build/test flags] [packages] [build/test flags & test binary flags]
你可以直接跑當前目錄,也可以指定 package,他會找所有 _test.go
的檔案執行
$ ~/.g/s/g/j/test-example go test
PASS
ok github.com/jaychung/test-example 0.005s
再來你可能會想說,如果一個 project 裡有很多 package,要怎麼執行全部的 test 呢?
$ ~/.g/s/g/j/test-example go test ./...
ok github.com/jaychung/test-example 0.005s
只要這樣就可以囉!