Lesson 2 · Unit 04
Tests and tools
Table-driven tests, go test, benchmarks, vet, gofmt and modules.
What you practise
- Table-driven tests,
go test, benchmarks,go vetandgofmt, modules andgo.mod
Try a question from this lesson
Pick one
Go finds tests by name, as pytest does: functions starting with Test, in files ending _test.go. Trace this one (code and test shown together). What does go test say?
package mathx
import "testing"
func Abs(n int) int {
if n < 0 {
return n
}
return n
}
func TestAbs(t *testing.T) {
if got := Abs(-3); got != 3 {
t.Errorf("Abs(-3) = %d, want 3", got)
}
}Correct answer
FAIL: Abs(-3) = -3, want 3
Why
Abs has a bug: the negative branch returns n unchanged. The test gets -3, and t.Errorf marks the test as failed and formats the message. There is no assert library in the standard toolkit: a test is an if and a call on t.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
go test
Tests live next to the code in files named something_test.go. Each test is a function TestXxx(t *testing.T). The go test command builds the package together with its test files, runs every test and prints the failures.
t.Errorf records a failure and lets the test continue, so one run can report several problems. t.Fatalf records it and stops that test at once.
$ go test
--- FAIL: TestAbs (0.00s)
abs_test.go:8: Abs(-3) = -3, want 3
FAIL
exit status 1
FAIL shop/mathx 0.003sConcept
Table-driven tests
To test many inputs, Go programmers do not write many test functions. They write a table: a slice of small structs, one row per case, each with an input and the wanted result. One loop runs them all.
Adding a case is adding a line. Use Errorf, not Fatalf, so one bad row does not hide the others, and put the input in the message so the failure says which row it was.
func TestSign(t *testing.T) {
tests := []struct{ in, want int }{
{5, 1}, {-2, -1}, {0, 0},
}
for _, tc := range tests {
got := Sign(tc.in)
if got != tc.want {
t.Errorf("Sign(%d) = %d, want %d",
tc.in, got, tc.want)
}
}
}Concept
gofmt, go vet and go.mod
gofmt rewrites source into the one standard layout, so nobody argues about style; editors run it on every save. go vet reports code that compiles but is probably wrong, such as a Printf verb that does not fit its argument.
A module is a tree of packages with a go.mod file at its root: the module path that imports start with, the Go version, and the exact version of each dependency. go mod tidy keeps it in step with your imports.
module example.com/shop
go 1.24
require example.com/money v1.4.29 more exercises in the app
- 3× type the answer
- 4× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.