Writing Unit Tests
Start with Writing Unit Tests
In this lesson, explore writing unit tests through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of writing unit tests.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A unit test checks one small behavior under controlled conditions. Functions named TestXxx(t *testing.T) in _test.go files are discovered automatically.
Use t.Errorf to report a failure and continue checking; use t.Fatalf when continuing would not make sense.
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
unit_test.go
package main
import "testing"
func TestIsEven(t *testing.T) {
if !isEven(2) { t.Error("2 should be even") }
if isEven(3) { t.Error("3 should be odd") }
}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 isEven(n int) bool { return n%2 == 0 }
func main() {
fmt.Println("2 even:", isEven(2))
fmt.Println("3 even:", isEven(3))
}
Output
2 even: true
3 even: falseTrace what the program does
The function reports true for 2 and false for 3. A test can assert both expectations and report a precise error when a regression occurs.
Avoid common mistakes
- Test exported and unexported behavior through useful package boundaries.
- Avoid brittle assertions against incidental implementation details.
Try it yourself
Write TestIsEven to check 0, 2, 3 and -4.
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 Writing Unit Tests 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.