golang test測試使用


1.創建測試文件夾mysql,文件夾下的go文件的package必須與文件夾名一致(不然會識別不到)

2.創建需要測試的文件mysql.go(使用github.com/go-sql-driver/mysql包)

package mysql

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

func findByPk(pk int) int {
    var num int = 0
    db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/plugin_master?charset=utf8")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    stmtOut, err := db.Prepare("select id from t_admin where id=?")
    if err != nil {
        panic(err.Error())
    }
    defer stmtOut.Close()

    err = stmtOut.QueryRow(pk).Scan(&num)
    if err != nil {
        panic(err.Error())
    }
    return num
}
View Code

3.創建單元測試用例文件mysql_test.go(文件名必須是*_test.go的類型,*代表要測試的文件名,函數名必須以Test開頭如:TestXxx或Test_xxx)

package mysql

import (
    "testing"
)

func Test_findByPk(t *testing.T) {
    num := findByPk(1)
    t.Log(num)
}
View Code
測試所有的文件 go test,將對當前目錄下的所有*_test.go文件進行編譯並自動運行測試。
測試某個文件使用”-file”參數。go test –file *.go 。例如:go test -file mysql_test.go,"-file"參數不是必須的,可以省略,如果你輸入go test b_test.go也會得到一樣的效果。
測試某個方法 go test -run='Test_xxx'
"-v" 參數 go test -v ... 表示無論用例是否測試通過都會顯示結果,不加"-v"表示只顯示未通過的用例結果

4.創建benchmark性能測試用例文件mysql_b_test.go(文件名使用*_b_test.go的類型(也可直接放在test文件中),*代表要測試的文件名,函數名必須以Benchmark開頭如:BenchmarkXxx或Benchmark_xxx)

package mysql

import (
    "testing"
)

func Benchmark_findByPk(b *testing.B) {
    for i := 0; i < b.N; i++ { //use b.N for looping
        findByPk(1)
    }
}
View Code
進行所有go文件的benchmark測試 go test -bench=".*" 或 go test . -bench=".*"
對某個go文件進行benchmark測試 go test mysql_b_test.go -bench=".*"
測試單個文件時,找不到方法,似乎要引入文件吧(暫未測試)

5.用性能測試生成CPU狀態圖(暫未測試使用)

使用命令:
go test -bench=".*" -cpuprofile=cpu.prof -c
cpuprofile是表示生成的cpu profile文件
-c是生成可執行的二進制文件,這個是生成狀態圖必須的,它會在本目錄下生成可執行文件mysql.test
然后使用go tool pprof工具
go tool pprof mysql.test cpu.prof
調用web(需要安裝graphviz)來生成svg文件,生成后使用瀏覽器查看svg文件
參考 http://www.cnblogs.com/yjf512/archive/2013/01/18/2865915.html


免責聲明!

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



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