Course: Learning GO

A collection of go basic fundamentals, syntax and concepts.

Table of contents

Lesson: Testing

Testing

  • Vanilla GO includes testing
  • A test is a file with suffix_test.go
  • You define functions with prefix Test and with an special signature receiving a *testing.T argument
  • You can create subtests as goroutines
  • You use CLI with go test
  • TableDrivenTest Design Pattern
  • Fuzzing
    Automated testing that manipulates inputs to find bugs. Go fuzzing uses converage guaidance to find failures and is valuable in detection security exploits and vulnerabilities.

Example


func TestMergeSort(t *testing.T) {
	var tests = []struct {
		input    []int
		expected []int
	}{
		{[]int{5, 2, 8, 3, 1, 9, 4, 7, 6}, []int{1, 2, 3, 4, 5, 6, 7, 8, 9}},
		{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, []int{1, 2, 3, 4, 5, 6, 7, 8, 9}},
		{[]int{9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5, 6, 7, 8, 9}},
		{[]int{9, 4, 5, 3, 2, 1}, []int{1, 2, 3, 4, 5, 9}},
		{[]int{}, []int{}},
		{[]int{1}, []int{1}},
	}
	for _, tt := range tests {
		res := mergeSort(tt.input)
		if !reflect.DeepEqual(res, tt.expected) {
			t.Errorf("got = %v, expected %v", tt.input, tt.expected)
		}
	}
}