Goland 为函数快捷创建测试方法

25 min read

Goland 确实为函数快捷创建测试方法提供了很方便的功能。只需要在函数的声明上方输入“Test”并按下 Tab 键,即可自动生成一个测试函数。

例如,对于以下函数:

func Add(a, b int) int {
    return a + b
}

如果想为其创建测试方法,只需要在其声明上方输入“Test”:

func TestAdd(t *testing.T) {
    // test code here
}

然后按下 Tab 键即可自动生成一个测试方法的模板:

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

然后我们就可以在生成的测试方法中添加多组测试输入和期望输出,来对该函数进行测试。