golang test techniques

func twoSum(nums []int, target int) []int {
	for i := 0; i < len(nums); i++ {
		for j := i + 1; j < len(nums); j++ {
			if nums[i]+nums[j] == target {
				return []int{i, j}
			}
		}
	}
	return []int{0, 0}
}

table driven test

func TestAddTwo(t *testing.T) {
	var addTwoTests = []struct {
		nums     []int
		target   int
		expected []int
	}{
		{[]int{2, 7, 11, 15}, 9, []int{0, 1}},
		{[]int{3, 2, 4}, 6, []int{1, 2}},
	}

	for _, tt := range addTwoTests {
		if result := twoSum(tt.nums, tt.target); !reflect.DeepEqual(result, tt.expected) {
			t.Fatalf("should be %v, but is:%v\n", tt.expected, result)
		}
	}
}

gocheck

func Test(t *testing.T) { TestingT(t) }

type TestSuite struct{}

var _ = Suite(&TestSuite{})

func (s *TestSuite) TestAddTwo(c *C) {

	var addTwoTests = []struct {
		nums     []int
		target   int
		expected []int
	}{
		{[]int{2, 7, 11, 15}, 9, []int{0, 1}},
		{[]int{3, 2, 4}, 6, []int{1, 2}},
	}

	for _, tt := range addTwoTests {
		result := twoSum(tt.nums, tt.target)
		c.Check(result, DeepEquals, tt.expected)
	}
}

using github.com/stretchr/testify library

参考

go 单元测试进阶篇 - 腾云阁 - 腾讯云