Subtests
Start with Subtests
In this lesson, explore subtests through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of subtests.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
t.Run creates named subtests. They appear in go test -v output and can be filtered with go test -run.
A parent test can share setup while subtests keep individual cases separately diagnosable. Use t.Parallel only when data and resources are safe to share.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Named subtests
package main
import "testing"
func TestLength(t *testing.T) {
t.Run("empty", func(t *testing.T) { if length("") != 0 { t.Error("want zero") } })
t.Run("ascii", func(t *testing.T) { if length("Go") != 2 { t.Error("want two bytes") } })
}Run go test -v -run TestLength.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func length(s string) int { return len(s) }
func main() {
cases := map[string]string{"empty": "", "ascii": "Go"}
fmt.Println("empty:", length(cases["empty"]))
fmt.Println("ascii:", length(cases["ascii"]))
}
Output
empty: 0
ascii: 2Trace what the program does
The standalone program shows two named cases. A real TestLength uses t.Run for each descriptive name and gives each failure separate context.
Avoid common mistakes
- Subtests run within their parent test’s lifetime.
- Parallel subtests should not mutate shared test data unsafely.
Try it yourself
Write a TestLength using subtests empty, ascii and multibyte.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Subtests in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.