Go: Table-driven unit tests

Here is the code we want to test:

package search

// Find returns the smallest index i at which x <= a[i].
// If there is no such index, it returns len(a).
// The slice must be sorted in ascending order.
func Find(a []int, x int) int {
	// binary search
	i, j := 0, len(a)
	for i < j {
		m := i + (j-i)/2
		// i ≤ m < j
		if x > a[m] {
			i = m + 1
		} else {
			j = m
		}
	}
	return i
}
  • Put the test code in a file whose name ends with _test.go.
  • Write a function TestXXX with a single argument of type *testing.T. The test framework runs each such function.
  • To indicate a failed test, call a failure function such as t.Errorf.
package search

import "testing"

var tests = []struct {
	a   []int
	x   int
	exp int
}{
	{[]int{}, 1, 0},
	{[]int{1, 2, 3, 3}, 0, 0},
	{[]int{1, 2, 3, 3}, 1, 0},
	{[]int{1, 2, 3, 3}, 2, 1},
	{[]int{1, 2, 3, 3}, 3, 3}, // Here's an error.
	{[]int{1, 2, 3, 3}, 4, 4},
}

func TestFind(t *testing.T) {
	for _, e := range tests {
		res := Find(e.a, e.x)
		if res != e.exp {
			t.Errorf("Find(%v, %d) = %d, expected %d",
				e.a, e.x, res, e.exp)
		}
	}
}

Run the tests with go test:

$ go test
--- FAIL: TestFind (0.00s)
	search_test.go:22: Find([1 2 3 3], 3) = 2, expected 3
FAIL
exit status 1
FAIL	.../search	0.001s

Comments

Be the first to comment!