wtysos11 / blogWiki

Use to store public paper and organize them.
17 stars 4 forks source link

golang单元测试整理归纳 #184

Closed wtysos11 closed 3 years ago

wtysos11 commented 3 years ago

本文目的 复习并整理go test相关知识 要求:能让我在短时间内通过阅读该文掌握写一份go单元测试所需要的知识

参考资料

基础知识

一般测试文件应该与被测试文件放在同一个目录下,比如被测试代码为intutils.go时,被测试代码应该写为intutils_test.go

通常会编写一个名称以Test开头的函数来创建测试(这个我记得是必须的,不然识别不出来)。例如GoLand自动生成的测试文件(Alt+Insert,之前写Java的时候经常用这个来生成DAO)

func TestTest(t *testing.T) {
    type args struct {
        a int
    }
    tests := []struct {
        name string
        args args
        want int
    }{
        // TODO: Add test cases.
//{name,args{},want},...
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Test(tt.args.a); got != tt.want {
                t.Errorf("Test() = %v, want %v", got, tt.want)
            }
        })
    }
}

一些常用函数: