go test 初始化--- TestMain的使用


go test 功能,提高了開發和測試的效率。
有時會遇到這樣的場景:
進行測試之前需要初始化操作(例如打開連接),測試結束后,需要做清理工作(例如關閉連接)等等。這個時候就可以使用TestMain()。

下面例子的文件結構如下:

hello/add.go
hello/test_add.go

add.go文件

package hello

func Add(a,b int) int {

	return a+b
}

add_test.go文件

package hello

import(
	"fmt"
	"testing"
)

func TestAdd(t *testing.T) {

        r := Add(1, 2)
        if r !=3 {

                t.Errorf("Add(1, 2) failed. Got %d, expected 3.", r)
        }

}


func TestMain(m *testing.M) {
	fmt.Println("begin")
	m.Run()
	fmt.Println("end")
}

測試從TestMain進入,依次執行測試用例,最后從TestMain退出。

$ go test –v

output:

begin
=== RUN TestAdd
--- PASS: TestAdd (0.00s)
PASS
end
ok hello 0.432s


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM