Jex’s Note

Golang 測試

原生 testing

Commands

執行當下目錄的 test

go test

執行所有 test 包括子目錄

go test ./...

ignore 某個 package

go test `go list ./... | grep -v your_go_app/utilities`

test 特定的 package

go test your_go_app/utilities/ip

First example

import "testing"

func Sum(x int, y int) int {
    return x + y
}

func TestSum(t *testing.T) {
    total := Sum(5, 5)
    if total != 10 {
       t.Errorf("Sum was incorrect, got: %d, want: %d.", total, 10)
    }
}

Ginkgo

Ginkgo 是一套 Golang BDD Testing Framework

Install

go get github.com/onsi/ginkgo/ginkgo
go get github.com/onsi/gomega

Create first test

Init

ginkgo bootstrap
ginkgo generate [app_name]

user_test.go :

var _ = Describe("User", func() {
    Describe("Test User", func() {
        Context("with SetName", func() {
            data := map[string]interface{}{
                "Name":       "Jex",
                "Address":    "Taiwan",
            }
            It("should be a empty errMsg", func() {
                Expect(SetName(data)).To(Equal(""))
            })
        })
    })
})

Run

$ ginkgo

...略...
Ran 3 of 3 Specs in 6.895 seconds
SUCCESS! -- 3 Passed | 0 Failed | 0 Pending | 0 Skipped PASS

BeforeEach 在每個 Context 跑之前先執行

var _ = Describe("Sample", func() {
    Describe("XXX", func() {
        Describe("FFF", func() {
            var qq string
            BeforeEach(func() {
                qq = "XXX"
                fmt.Println("BeforeEach")
            })
            Context("Valid inputs for add function", func() {
                It("TTT", func() {
                    qq = "ZZZZZ"
                    fmt.Println(qq)
                    Expect(4).Should(Equal(4))
                })
                It("TTT", func() {
                    fmt.Println(qq)
                    Expect(4).Should(Equal(4))
                })
            })
        })
    })
})

結果 :

BeforeEach      // qq = XXX
ZZZZZ           // qq = ZZZZ
BeforeEach      // qq = XXX
XXX             // qq = XXX
  • 不管是 BeforeEach 賦與的變數或不同地方賦與的變數都要在 It 裡面才拿得到,在 It 外是取不到的,不知道是什麼原因?
  • Describe / Context 似乎是用 goroutine 去跑的,如果有些值要先等前一個 Describe/context Set 完,執行時可能不會有你預期的結果,有可能根本沒 Set 到就先執行那段了

ref:

Comments