Tests that come in the box
Go ships its test runner with the language. Put tests in a file ending in _test.go, write functions named TestXxx(t *testing.T), and run go test. No framework to choose, no configuration. Kernighan and Donovan devote chapter 11 to it, and *100 Go Mistakes* ends with a whole chapter of testing advice — the most famous being: use table-driven tests (mistake #85).
Today you'll write tests, and then the course will check them the way a good reviewer would: by quietly breaking the function in a few realistic ways and seeing whether your tests notice.
In a real project the tests live in their own _test.go file next to the code. Here both share one editor: when your file has Test functions and no main, the simulator runs them like go test -v.
testing.T
A test function receives a *testing.T. t.Errorf(…) reports a failure and keeps going, so you see every broken case in one run; t.Fatalf(…) reports and stops that test at once — use it when continuing makes no sense, such as after a failed setup. t.Log prints only when you ask for verbose output (-v) or the test fails.
package main
import "testing"
func Add(a, b int) int { return a + b }
func TestAdd(t *testing.T) {
got := Add(2, 3)
if got != 5 {
t.Errorf("Add(2, 3) = %d; want 5", got)
}
}
func TestAddNegative(t *testing.T) {
if got := Add(-2, -3); got != -6 {
t.Errorf("Add(-2, -3) = %d; want -6", got)
}
}