Go unitest

待测试:

// add.go

package util

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

使用gotests工具,自动生成测试用例框架:

https://github.com/cweill/gotests

gotests --help

add_test.go

package util

import "testing"

func TestAdd(t *testing.T) {
	type args struct {
		a int
		b int
	}
	tests := []struct {
		name string
		args args
		want int
	}{
		// TODO: Add test cases.
		{
			name: "case1",
			args: args{1, 2},
			want: 3,
		},
		{
			name: "case2",
			args: args{3, 6},
			want: 8,
		},
		{
			name: "case3",
			args: args{1, 4},
			want: 4,
		},
		{
			name: "case4",
			args: args{13, 6},
			want: 19,
		},
		{
			name: "case5",
			args: args{1, 16},
			want: 17,
		},
	}
	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)
			}
		})
	}
}

  

测试:

go test

结果:

--- FAIL: TestAdd (0.00s)
--- FAIL: TestAdd/case2 (0.00s)
add_test.go:45: Add() = 9, want 8
--- FAIL: TestAdd/case3 (0.00s)
add_test.go:45: Add() = 5, want 4
FAIL
exit status 1
FAIL _/Users/jerry/dev/demo/util 0.004s

原文地址:https://www.cnblogs.com/gm-201705/p/8192643.html