本文主要是介绍golang单测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
goland自动生成
- 鼠标移动到函数名处右击鼠标
- 点击:生成
- 点击:函数测试
func TestGetFieldIds(t *testing.T) {type args struct {fieldIdsStr string}tests := []struct {name stringargs argswantResult []uint}{// TODO: Add test cases.}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {if gotResult := GetFieldIds(tt.args.fieldIdsStr); !reflect.DeepEqual(gotResult, tt.wantResult) {t.Errorf("GetFieldIds() = %v, want %v", gotResult, tt.wantResult)}})}
}
由于goland自动生成的测试函数使用了反射,但是大多数情况下是不使用的,使用断言这种方式,所以就用了下面的Testify。
Testify
Testify是一个功能强大且易于使用的测试工具包,提供了丰富的断言方法和辅助函数。它扩展了Go的内置testing包,使测试编写更简洁、可读性更高。
导入库:go get github.com/stretchr/testify/assert
func TestGetFieldIds(t *testing.T) {testCases := []struct {input stringexpected []uint}{{input: "1,2,3,4,5", expected: []uint{1, 2, 3, 4, 5}},{input: "10,20,30", expected: []uint{10, 20, 30}},{input: "100,200,300,400", expected: []uint{100, 200, 300, 400}},// Add more test cases as needed}for _, tc := range testCases {result := GetFieldIds(tc.input)assert.Equal(t, tc.expected, result, "GetFieldIds result should match expected")}
}
这篇关于golang单测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!