golang 测试

说到测试,我们应该首先问自己这几个问题? 

  How:  怎么测试

  What: 测试什么

  Why:  为什么测试

怎么测?

下面这个例子:

package split

import "strings"

// Split slices into all substrings separated by sep and

// returns a slice of the substrings between those separators

func Split(s, sep string) []string {

        var result []string

        i := strings.Index(s, sep)

        for i > -1 {

                result =append(result, s[:i])

                s = s[i+len(sep):]

                i = strings.Index(s, sep)

        }   

        return append(result, s)

}

1. 测试函数必须以 Test开头

2. 测试函数必须有一个*testing.T参数,这个类型*testing.T 就是testing package注入类型(提供print,skip, fail the test方式) 

3. 测试代码应该单独起一个文件,后缀是_test.go

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        got := Split("a/b/c", "/")

        want := []string{"a", "b", "c"}

        if !reflect.DeepEqual(want, got) {

                t.Fatalf("expected: %v, got: %v", want, got)

        }   

}

怎么运行测试: 

go test 将运行当前目录下的测试

ccli@ccli-mac:split$ ls

split.go split_test.go

ccli@ccli-mac:unittest$ go test

PASS

ok _/Users/ccli/test/go/src/split 0.005s

如果你想运行项目下的多个package 测试,你可以用这个命令

go test ./...

ccli@ccli-mac:splitt$ go test ./...

ok _/Users/ccli/test/go/src/split 0.005s

怎么统计code coverage

export GOPATH=/Users/ccli/test/go

ccli@ccli-mac:split$ go test -coverprofile=cover.out

PASS

coverage: 100.0% of statements

ok split 0.005s

ccli@ccli-mac:split$ go tool cover -func=cover.out

split/split.go:7: Split 100.0%

total: (statements) 100.0%

ccli@ccli-mac:split$ go tool cover -html=cover.out -o cover.html

ccli@ccli-mac:split$ ls

cover.html cover.out split.go split_test.go

ccli@ccli-mac:split$

code coverage is 100%, 但是其实测试是欠缺的,我们并没有测试边界条件

1. 测试以逗号',"分开

2. 测试没有分隔符的源串

3. 测试以下划线结尾的源串

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests := []struct {

                inputstring

                sep  string

                want  []string

        }{ 

                {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                {input:"a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                {input:"abc", sep: "/", want: []string{"abc"}},

        }   

        for i, tc := range tests {

                got := Split(tc.input, tc.sep)

                if !reflect.DeepEqual(tc.want, got) {

                        t.Fatalf("test %d: expected: %v, got: %v", i+1, tc.want, got)

                }   

        }   

}

Test case里含有索引来表明第几个case failed

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

--- FAIL: TestSplit (0.00s)

split_test.go:22: test 3: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.005s



还有一种例子是以case名字来表示。

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests := []struct {

                namestring

                inputstring

                sep  string

                want  []string

        }{

                {name:"simple", input: "a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                {name:"wrong sep", input: "a/b/c", sep: ",", want: []string{"a/b/c"}},

                {name:"trailing sep", input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                {name:"no sep", input: "abc", sep: "/", want: []string{"abc"}},

        }

        for _, tc := range tests {

                got := Split(tc.input, tc.sep)

                if !reflect.DeepEqual(tc.want, got) {

                        t.Fatalf("case: %s: expected: %v, got: %v", tc.name, tc.want, got)

                }

        }

}


ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

--- FAIL: TestSplit (0.00s)

split_test.go:23: case: trailing sep: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.007s


还有一种是以map来存储case, as we know, map key is not predefined order, 更利于测试的随机性,来发现固定顺序不能发现的错误

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                namestring

                inputstring

                sep  string

                want  []string

        }{ 

                "simple": {input: "a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep": {input: "a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep": {input: "abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                got := Split(tc.input, tc.sep)

                if !reflect.DeepEqual(tc.want, got) {

                        t.Fatalf("case: %s: expected: %v, got: %v", name, tc.want, got)

                }   

        }   

}


ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

--- FAIL: TestSplit (0.00s)

split_test.go:23: case: trailing sep: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.005s


Fatalf 会终止测试函数,这样会导致后面case并没有跑到,不能一次看到all test case结果,因此可以用Errorf

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                namestring

                inputstring

                sep  string

                want  []string

        }{ 

                "simple": {input: "a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep": {input: "a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep": {input: "abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                got := Split(tc.input, tc.sep)

                if !reflect.DeepEqual(tc.want, got) {

                        t.Errorf("case: %s: expected: %v, got: %v", name, tc.want, got)

                }   

        }   

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

--- FAIL: TestSplit (0.00s)

split_test.go:23: case: trailing sep: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.005s

令人开心的是,sub test 在go 1.7版本中诞生了

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                name  string

                inputstring

                sep  string

                want  []string

        }{ 

                "simple":      {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep":    {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep":      {input:"abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                t.Run(name,func(t *testing.T) {

                        got := Split(tc.input, tc.sep)

                        if !reflect.DeepEqual(tc.want, got) {

                                t.Fatalf("expected: %v, got: %v", tc.want, got)

                        }   

                }) 

        }   

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

=== RUN  TestSplit/simple

=== RUN  TestSplit/wrong_sep

=== RUN  TestSplit/trailing_sep

=== RUN  TestSplit/no_sep

--- FAIL: TestSplit (0.00s)

    --- PASS: TestSplit/simple (0.00s)

    --- PASS: TestSplit/wrong_sep (0.00s)

    --- FAIL: TestSplit/trailing_sep (0.00s)

split_test.go:24: expected: [a b c], got: [a b c ]

    --- PASS: TestSplit/no_sep (0.00s)

FAIL

exit status 1

FAIL split 0.005s

You can also run sub tests by name using the `-run` flag

ccli@ccli-mac:split$ go test -run=.*/trailing -v

=== RUN  TestSplit

=== RUN  TestSplit/trailing_sep

--- FAIL: TestSplit (0.00s)

    --- FAIL: TestSplit/trailing_sep (0.00s)

split_test.go:24: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.006s

从结果上,我们并不能清晰的看出错误结果的区别在哪里。

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                name  string

                inputstring

                sep  string

                want  []string

        }{ 

                "simple":      {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep":    {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep":      {input:"abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                t.Run(name,func(t *testing.T) {

                        got := Split(tc.input, tc.sep)

                        if !reflect.DeepEqual(tc.want, got) {

                                t.Fatalf("expected: %#v, got: %#v", tc.want, got)

                        }   

                }) 

        }   

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

=== RUN  TestSplit/simple

=== RUN  TestSplit/wrong_sep

=== RUN  TestSplit/trailing_sep

=== RUN  TestSplit/no_sep

--- FAIL: TestSplit (0.00s)

    --- PASS: TestSplit/simple (0.00s)

    --- PASS: TestSplit/wrong_sep (0.00s)

    --- FAIL: TestSplit/trailing_sep (0.00s)

split_test.go:24: expected: []string{"a", "b", "c"}, got: []string{"a", "b", "c", ""}

    --- PASS: TestSplit/no_sep (0.00s)

FAIL

exit status 1

FAIL split 0.006s


如果想打印的更加直观,大家可以用下面这几个package

https://github.com/k0kubun/pp

https://github.com/davecgh/go-spew

https://github.com/google/go-cmp

package split

import (

        "testing"

        "github.com/google/go-cmp/cmp"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                name  string

                inputstring

                sep  string

                want  []string

        }{

                "simple":      {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep":    {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep":      {input:"abc", sep: "/", want: []string{"abc"}},

        }

        for name, tc := range tests {

                t.Run(name,func(t *testing.T) {

                        got := Split(tc.input, tc.sep)

                        diff := cmp.Diff(tc.want, got)

                        if diff != "" {

                        t.Fatalf(diff)

                        }

                })

        }

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

=== RUN  TestSplit/simple

=== RUN  TestSplit/wrong_sep

=== RUN  TestSplit/trailing_sep

=== RUN  TestSplit/no_sep

--- FAIL: TestSplit (0.00s)

    --- PASS: TestSplit/simple (0.00s)

    --- PASS: TestSplit/wrong_sep (0.00s)

    --- FAIL: TestSplit/trailing_sep (0.00s)

split_test.go:25:   []string{

"a",

"b",

"c",

+ "",

}

    --- PASS: TestSplit/no_sep (0.00s)

FAIL

exit status 1

FAIL split 0.006s


现在可以fix程序来解决这个failure了

package split

import "strings"

// Split slices into all substrings separated by sep and

// returns a slice of the substrings between those separators

func Split(s, sep string) []string {

        var result []string

        i := strings.Index(s, sep)

        for i > -1 {

                result =append(result, s[:i])

                s = s[i+len(sep):]

                i = strings.Index(s, sep)

        }   

        if len(s) > 0{ 

                result =append(result, s)

        }   

        return result

}


package split

import (

        "testing"

        "github.com/google/go-cmp/cmp"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                name  string

                inputstring

                sep  string

                want  []string

        }{ 

                "simple":      {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep":    {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep":      {input:"abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                t.Run(name,func(t *testing.T) {

                        got := Split(tc.input, tc.sep)

                        diff := cmp.Diff(tc.want, got)

                        if diff != "" {

                        t.Fatalf(diff)

                        }   

                }) 

        }   

}


ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

=== RUN  TestSplit/simple

=== RUN  TestSplit/wrong_sep

=== RUN  TestSplit/trailing_sep

=== RUN  TestSplit/no_sep

--- PASS: TestSplit (0.00s)

    --- PASS: TestSplit/simple (0.00s)

    --- PASS: TestSplit/wrong_sep (0.00s)

    --- PASS: TestSplit/trailing_sep (0.00s)

    --- PASS: TestSplit/no_sep (0.00s)

PASS

ok split 0.005s


测试什么?

C code unit is function 函数

Java code unit is class

Golang code unit is package

Test the behaviour of your unit, not its implementation, So we should test our packages behaviour via their public api

为什么测试

如果你不测试,那么产品最终被用户使用,用户使用也可以说验收测试,那时的问题将极大影响产品的信誉,因此尽早发现测试是软件从业者的目标。

测试应当由开发人员来承担,而不应该由专门的测试人员负责,测试应该是自动化的,这样一方面make sure 产品质量,另一方面也能提高开发效率,这里并没有说不需要的测试人员,而是说单元测试,功能测试集成测试都应该mock环境尽可能自动化。特殊情况下才有极少的专门测试人员来负责相应测试。


测试进阶

展示了怎么写Unit Test及怎么统计coverage, 为了方便写UT,最好exposed Api is Method not function,为了更好的帮助大家理解,给出了一个例子方便大家参考。例子分为三部分,source code, unit test code, Makefile.

Code 目录

mkdir -p ~/test/src/gounit/etcd

source code

package etcd

import (

        "context"

        "log"

        "time"

        "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"

        "go.etcd.io/etcd/clientv3"

)

type KV interface {

        Put(ctx context.Context, key, valstring, opts ...clientv3.OpOption) (*clientv3.PutResponse, error)

}

type etcdClient struct {

        kv KV

}

const (

        DefaultOperationTimeout =3 * time.Second

)

var (

        endpoints = []string{"localhost:2379"}

)

func (ec *etcdClient) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) {

        ctx, cancel := context.WithTimeout(ctx, DefaultOperationTimeout)

        resp, err := ec.kv.Put(ctx, key, val, opts...)

        cancel()

        if err != nil {

                switch err {

                case context.Canceled:

                        log.Printf("[ETCD] ctx is canceled by another routine: %v", err)

                case context.DeadlineExceeded:

                        log.Printf("[ETCD] ctx is attached with a deadline is exceeded: %v", err)

                case rpctypes.ErrEmptyKey:

                        log.Printf("[ETCD] client-side error: %v", err)

                default:

                        log.Printf("[ETCD] bad cluster endpoints, which are not etcd servers: %v", err)

                }

        }

        return resp, err

}

Unit Test code

package etcd

import (

        "context"

        "errors"

        "testing"

        "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"

        "github.com/stretchr/testify/assert"

        "go.etcd.io/etcd/clientv3"

)

type mockEtcdClient struct {

}

var (

        defaultErr = errors.New("default err")

)

func (mec *mockEtcdClient) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) {

        switch key {

        case "canceled":

                return nil, context.Canceled

        case "deadline_exceeded":

                return nil, context.

        case "err_empty_key":

                return nil, rpctypes.ErrEmptyKey

        case "default":

                return nil, defaultErr

        default:

                return nil, nil

        }

}

type putResult struct {

        putResponse *clientv3.PutResponse

        err        error

}

func TestPut(t *testing.T) {

        api := &etcdClient{kv: &mockEtcdClient{}}

        tests := []struct {

                key    string

                expect putResult

        }{

                {

                        key:"canceled",

                        expect: putResult{

                                putResponse:nil,

                                err:        context.Canceled,

                        },

                },

                {

                        key:"deadline_exceeded",

                        expect: putResult{

                                putResponse:nil,

                                err:        context.DeadlineExceeded,

                        },

                },

                {

                        key:"err_empty_key",

                        expect: putResult{

                                putResponse:nil,

                                err:        rpctypes.ErrEmptyKey,

                        },

                },

                {

                        key:"default",

                        expect: putResult{

                                putResponse:nil,

                                err:        defaultErr,

                        },

                },

                {

                        key:"fine",

                        expect: putResult{

                                putResponse:nil,

                                err:        nil,

                        },

                },

        }

        for index, test := range tests {

                _, err := api.Put(context.Background(), test.key,"oktestut")

                assert.EqualValuesf(t, test.expect.err, err,"case: %d", index)

        }

}

Makefile

export GOPATH = $(shell pwd)/../../..

TEST_FLAGS=-test.short -v

PKGS = gounit/etcd

print:

        echo$(GOPATH)

dep:

        go get "go.etcd.io/etcd/clientv3"

        go get "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"

        go get "github.com/stretchr/testify/assert"

vet:dep 

        go fmt ./...

        go vet ./...

test:vet 

        go test --cover$(PKGS)

cover-tool:

        go get github.com/jstemmer/go-junit-report

        go get golang.org/x/tools/cmd/cover

        go get github.com/axw/gocov/gocov

        go get github.com/AlekSi/gocov-xml

        go get github.com/wadey/gocovmerge

unit-coverage: dep cover-tool

        mkdir -p report

        cat /dev/null > report/utest.out

        $(foreach i,$(PKGS),go test $(i) $(TEST_FLAGS) --covermode=count -coverprofile=report/cover-`echo $(i) |sed 's/\//./g'`.out >> report/utest.out;)

        cat report/utest.out | go-junit-report > report/unit_test_report.xml

        gocovmerge report/cover-*.out > report/unit_test_coverage.out

        gocov convert report/unit_test_coverage.out | gocov-xml > report/unit_test_coverage.xml

        go tool cover -html=report/unit_test_coverage.out -o report/unit_test_coverage.html

        rm report/{cover-*,utest}.out

clean:

        rm -rf report 

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,277评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,777评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,946评论 0 245
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,271评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,636评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,767评论 1 221
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,989评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,733评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,457评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,674评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,155评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,518评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,160评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,114评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,898评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,822评论 2 280
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,705评论 2 273