Skip to content

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

  1. _test.go: The naming rule for test files.
  2. testing.T: The object used to report errors.
  3. 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! :::