Understand the contract
Go finds tests in files ending in _test.go. A test function begins with Test and receives *testing.T. Run go test ./... from the module root. Useful tests state expected behavior independently of the implementation and include inputs that could reveal a mistake, not only the happy path.
A table-driven test stores inputs and expected results in a slice of cases. t.Run names each case so failures identify the condition that broke. Keep each expectation simple enough to inspect. Reimplementing the production algorithm inside the test can reproduce the same bug instead of detecting it.
Work through the example
The example belongs in sum_test.go inside a separate practice directory. It includes a small sum function so the test can run independently. Nil, positive and mixed-sign inputs exercise distinct behavior. Failure messages include actual and expected results rather than merely saying that the test failed.
package main
import "testing"
func sum(values []int) int {
total := 0
for _, v := range values { total += v }
return total
}
func TestSum(t *testing.T) {
cases := []struct { name string; values []int; want int }{
{"empty", nil, 0},
{"positive", []int{2, 3}, 5},
{"mixed", []int{-2, 5}, 3},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := sum(tc.values); got != tc.want {
t.Fatalf("sum(%v) = %d; want %d", tc.values, got, tc.want)
}
})
}
}Watch this boundary
Passing tests only support the cases and properties actually checked. Coverage can reveal unexecuted code but does not prove a correct assertion. Avoid sleep-based timing assumptions in concurrent tests; synchronize explicitly and use httptest for HTTP behavior without depending on a manually started service.
Practice with a changed input
Introduce a deliberate bug that ignores negative values and check which case fails. Add a case with canceling values such as 5 and -5, then restore the implementation.
Lesson 41 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services