Test helpers
- Go course
- Intermediate
- Lesson 44/80
- 4 min
Learn helpers like t.Helper and t.Cleanup.
Test helpers
Move repeated checks into helper functions and add t.Helper() at the top; then the failure line points to the test line calling the helper, not inside it:
func esit(t *testing.T, got, want int) {
t.Helper()
if got != want {
t.Errorf("got %d, want %d", got, want)
}
}For resources needing setup, t.Cleanup(f) registers cleanup to run when the test ends; t.TempDir() gives a temporary folder that is deleted automatically.
Parallel tests and TestMain
Tests that call t.Parallel() run concurrently with the package's other parallel tests, speeding up slow I/O tests. If the whole package needs one-time setup, write TestMain(m *testing.M):
func TestMain(m *testing.M) {
db := kur()
kod := m.Run()
db.Close()
os.Exit(kod)
}Practice Cleanup order
Imitate t.Cleanup's LIFO behavior with defer: inside calistir(), register defer fmt.Println("db kapandı") and then defer fmt.Println("dosya silindi"), then print "test".
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func calistir() {
defer fmt.Println("db kapandı")
defer fmt.Println("dosya silindi")
fmt.Println("test")
}
func main() {
calistir()
}Expected output
test dosya silindi db kapandı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In what order do functions registered with <code>t.Cleanup</code> run?
- Randomly
- In parallel
- Last registered runs first (LIFO) Correct answer
- In registration order
Explanation: Cleanup behaves like defer; the resource set up later is closed first.
2 Fix the line
func esit(t *testing.T, got, want string) {
t.____()
if got != want { t.Errorf("got %q, want %q", got, want) }
}
func esit(t *testing.T, got, want string) {
t.Helper()
if got != want { t.Errorf("got %q, want %q", got, want) }
}
Explanation: t.Helper marks the function as a helper; the failure location shows the calling line.
3 Helper and role
| Term | Meaning |
|---|---|
t.Helper() |
Correct failure line |
t.Cleanup(f) |
End-of-test cleanup |
t.TempDir() |
Temporary folder |
t.Parallel() |
Concurrent running |