Skip to content

Testing

Test files in go are kept alongside the source code with postfix _test.go. Functions beginning with Test* that take an argument (t *testing.T) will be run as unit tests. A test fails if a condition leading to t.Error or t.Fail is met.

bash
# Test everything in current directory
go test .

# Test everything in subdirectories
go test ./...

# See coverage percentage
go test -cover .

# Generate coverage file
go test -coverprofile=coverage.out .

# View code coverage from file
go tool cover -html=coverage.out

# Run individual test
go test -run Test_alpha_isPrime

# Run groups of tests
go test -run Test_alpha

Test cases

Within a test function, you can run multiple related test cases by iterating over a slice of cases with t.Run.

go
func Test_alpha_isPrime(t *testing.T) {
	primeTests := []struct {
		name     string
		num      int
		expected bool
		message  string
	}{
		{"prime", 7, true, "7 is prime!"},
		{"not prime", 8, false, "8 is not prime, it is divisible by 2"},
		{"zero", 0, false, "0 is not prime, by definition!"},
		{"one", 1, false, "1 is not prime, by definition!"},
		{"negative", -1, false, "Negative numbers are not prime, by definition!"},
	}

	for _, tt := range primeTests {
		t.Run(tt.name, func(t *testing.T) {
			actual, msg := isPrime(tt.num)
			if actual != tt.expected {
				t.Errorf("isPrime(%d): expected %t, actual %t", tt.num, tt.expected, actual)
			}
			if msg != tt.message {
				t.Errorf("isPrime(%d): expected %s, actual %s", tt.num, tt.message, msg)
			}
		})
	}
}