Module 1: Unit Testing (The Safety Inspector)
๐ Module 1: Unit Testing
Course ID: GO-301
Subject: The Safety Inspector
In Go, testing is built right into the language. You donโt need external libraries. A Senior Developer never says โI think it works.โ They say โMy tests prove it works.โ
๐๏ธ Step 1: The Test File
A test file always ends in _test.go.
๐งฉ The Analogy: The Safety Inspector
- You have your factory (The Code).
- The Safety Inspector (The Test File) arrives with a clipboard.
- They try to โBreakโ your code to see if it handles mistakes correctly.
๐๏ธ Step 2: Table-Driven Tests
Professional Go developers use Table-Driven Tests.
๐งฉ The Analogy: The Checklist
Instead of writing 10 separate tests, you write one Checklist (The Table) with inputs and expected outputs.
- Input: 2 + 2, Expected: 4
- Input: 10 + 0, Expected: 10
- Input: -1 + 5, Expected: 4
๐๏ธ Step 3: In Code
func TestAdd(t *testing.T) {
// 1. The Checklist (Table)
tests := []struct {
a, b, expected int
}{
{1, 1, 2},
{10, 20, 30},
{0, 0, 0},
}
// 2. Loop through the checklist
for _, tt := range tests {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("Error! %d + %d expected %d, but got %d", tt.a, tt.b, tt.expected, result)
}
}
}๐ฅ Module 1 Review
- _test.go: The naming rule for test files.
- testing.T: The object used to report errors.
- go test: The command to run your inspector.
:::tip Slow Learner Note Testing feels like โextra workโ at first. But it actually saves you time because you donโt have to restart your app and click buttons manually 100 times! :::