Testing Fundamentals

Overview

Go has built-in testing support. Test files end with _test.go and use the testing package.

Writing Tests

// math.go
package math

func Add(a, b int) int {
    return a + b
}
// math_test.go
package math

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Add(2, 3) = %d; want 5", result)
    }
}

Running Tests

go test              # Current package
go test ./...        # All packages
go test -v           # Verbose
go test -run TestAdd # Specific test

Test Functions

func TestXxx(t *testing.T)          // Test
func BenchmarkXxx(b *testing.B)     // Benchmark
func ExampleXxx()                   // Example
func FuzzXxx(f *testing.F)          // Fuzz test

t.Error vs t.Fatal

func TestExample(t *testing.T) {
    // Continues after failure
    t.Error("failed but continuing")

    // Stops test immediately
    t.Fatal("failed, stopping now")
}

Helper Functions

func assertEqual(t *testing.T, got, want int) {
    t.Helper()  // Marks this as helper
    if got != want {
        t.Errorf("got %d, want %d", got, want)
    }
}

func TestMath(t *testing.T) {
    assertEqual(t, Add(1, 2), 3)
}

Setup and Teardown

func TestMain(m *testing.M) {
    // Setup
    setup()

    code := m.Run()  // Run tests

    // Teardown
    teardown()
    os.Exit(code)
}

Parallel Tests

func TestParallel(t *testing.T) {
    t.Parallel()  // Run in parallel
    // Test code
}

Summary

Command Purpose
go test Run tests
go test -v Verbose output
go test -cover Show coverage
go test -race Race detection