testify: Testing in Go

假設你把 project 放在 $GOPATH/src/github.com/your_username/ 底下

test

in xxx_test.go

package pangu_test

import (
    "github.com/stretchr/testify/suite"
    "github.com/your_username/your_project"
    "testing"
)

type YourTestSuite struct {
    suite.Suite
}

func (suite *YourTestSuite) TestFunction1() {
    suite.Equal("expected", "actual")
}

// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestYourTestSuite(t *testing.T) {
    suite.Run(t, new(YourTestSuite))
}

go test 會自動執行當前目錄下的所有以 _test.go 結尾的檔案
更準確地說是執行所有以 Test 開頭的 functions

# run tests in the current directory
$ go test

# run tests in the current directory and sub-directories
$ go test ./...

ref:
http://golang.org/pkg/testing/
https://github.com/stretchr/testify

How to specify test resources?
https://groups.google.com/forum/#!topic/golang-nuts/VPVlIiO5yXw

example

in example_test.go

這個檔名是固定的
裡面的內容會出現在 godoc 的 Example 條目底下
確切地說
ExampleFunction1() 這個 function 的內容就會出現在 Function1() 的 Example 條目中
你可以執行 godoc -http=:6060 在本機查看

因為也是以 _test.go 結尾的關係
所以執行 go test 的時候也會執行這個檔案
貼心地幫你確認你的 example 程式碼是不是真的能夠動

package pangu_test

import (
    "fmt"
    "github.com/your_username/your_project"
)

func ExampleFunction1() {
    fmt.Println(`The knights who say "Ni"!`)
    // Output:
    // The knights who say "Ni"!
}

benchmark

in benchmark_test.go

這個檔名是固定的

package pangu_test

import (
    "testing"
)

func BenchmarkFunction1(b *testing.B) {
    for i := 0; i < b.N; i++ {
        doShit()
    }
}
# This will run tests and benchmarks
$ go test -bench=.

# If you want to skip the tests, you can do so by passing a regex to the -run flag that will not match anything. 
$ go test -run=XXX -bench=.

coverage

$ go test -cover -coverprofile=cover.out -covermode=count
$ go tool cover -func=cover.out
$ go tool cover -html=cover.out

# or

$ go test -cover -covermode=count ./...

Integrate with Travis CI and Coveralls

language: go

go:
  - 1.4.2
  - 1.4.1
  - 1.4
  - 1.3.3
  - 1.3.2
  - 1.3.1
  - 1.3
before_install:
  - go get github.com/axw/gocov/gocov
  - go get github.com/mattn/goveralls
  - go get golang.org/x/tools/cmd/cover
script:
  - goveralls -service=travis-ci

ref:
http://docs.travis-ci.com/user/languages/go/
https://coveralls.zendesk.com/hc/en-us/articles/201342809-Go