Go

Basic Unit Test with go test

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Tests live in `*_test.go` files alongside the code. Functions named `TestXxx(t *testing.T)` are picked up by `go test`. Use `t.Errorf` for soft fails (continues running), `t.Fatalf` for hard fails.
Go
Raw
// math.go
package mymath

func Add(a, b int) int { return a + b }

func Divide(a, b int) (int, error) {
    if b == 0 { return 0, fmt.Errorf("divide by zero") }
    return a / b, nil
}

// ─────────────────────────────────────────────────────────
// math_test.go
package mymath

import "testing"

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

func TestDivide(t *testing.T) {
    got, err := Divide(10, 2)
    if err != nil { t.Fatalf("unexpected error: %v", err) }
    if got != 5  { t.Errorf("Divide(10,2) = %d, want 5", got) }

    // Should error on divide by zero
    if _, err := Divide(1, 0); err == nil {
        t.Error("expected an error for divide by zero, got nil")
    }
}

// Run with:    go test ./...
// Verbose:     go test -v ./...
// Race detect: go test -race ./...
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.