go测试

单元测试

使用init方法初始化一些公用变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package db_conn_pool

import (
"context"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"testing"
"time"
)

const (
user = "root"
pw = "root"
ip = "127.0.0.1"
port = 3306
database = "test"
)

var (
ctx context.Context
db *sql.DB
)

func init() {
ctx = context.Background()
db, _ = sql.Open("mysql", user+":"+pw+"@tcp("+ip+":"+fmt.Sprintf("%d", port)+")/"+database+"?charset=utf8&autocommit=true&timeout=1s")
}

func Test_PingContext(t *testing.T) {

ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()

status := "up"
if err := db.PingContext(ctx); err != nil {
status = "down"
}
log.Println(status)
}

使用Go Test测试单个文件和单个方法

比如我们go get一个packet想跑下它的单元测试,可以cd到对应目录执行如下命令

测试单个方法

go test -v atomic_test.go -test.run TestSwapInt32

测试单个文件

go test -v atomic_test.go