Skip to main content

Overview

The testing package provides support for automated testing of Go packages. It is intended to be used in concert with the go test command, which automates execution of test functions.

Types

T

The T type is passed to test functions to manage test state and support formatted test logs.
type T struct {
    // contains filtered or unexported fields
}
A test ends when its Test function returns or calls any of the methods FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf.

Methods

Error
func(args ...any)
Equivalent to Log followed by Fail.
Errorf
func(format string, args ...any)
Equivalent to Logf followed by Fail.
Fail
func()
Marks the function as having failed but continues execution.
FailNow
func()
Marks the function as having failed and stops its execution by calling runtime.Goexit.
Failed
func() bool
Reports whether the function has failed.
Fatal
func(args ...any)
Equivalent to Log followed by FailNow.
Fatalf
func(format string, args ...any)
Equivalent to Logf followed by FailNow.
Helper
func()
Marks the calling function as a test helper function. When printing file and line information, that function will be skipped.
Log
func(args ...any)
Formats its arguments using default formatting, analogous to fmt.Println, and records the text in the error log.
Logf
func(format string, args ...any)
Formats its arguments according to the format, analogous to fmt.Printf, and records the text in the error log.
Name
func() string
Returns the name of the running test or subtest.
Parallel
func()
Signals that this test is to be run in parallel with (and only with) other parallel tests.
Run
func(name string, f func(t *T)) bool
Runs f as a subtest of t called name. It returns whether the subtest succeeded.
Skip
func(args ...any)
Equivalent to Log followed by SkipNow.
SkipNow
func()
Marks the test as having been skipped and stops its execution.
Skipf
func(format string, args ...any)
Equivalent to Logf followed by SkipNow.
Skipped
func() bool
Reports whether the test was skipped.
TempDir
func() string
Returns a temporary directory for the test to use. The directory is automatically removed when the test completes.
Cleanup
func(f func())
Registers a function to be called when the test and all its subtests complete.
Setenv
func(key, value string)
Calls os.Setenv and uses Cleanup to restore the environment variable to its original value after the test.

B

The B type is passed to benchmark functions to manage benchmark timing and control the number of iterations.
type B struct {
    N int // The number of iterations to run
    // contains filtered or unexported fields
}

Methods

Loop
func() bool
Reports whether the benchmark should continue running iterations. Modern benchmarks should use Loop instead of iterating over b.N.
ResetTimer
func()
Resets the benchmark timer. This can be used to ignore expensive setup before the benchmark loop.
StartTimer
func()
Starts timing a test. This function is called automatically before a benchmark starts.
StopTimer
func()
Stops timing a test. This can be used to pause the timer while performing complex initialization.
RunParallel
func(body func(*PB))
Runs a benchmark in parallel. It creates multiple goroutines and distributes iterations among them.
SetBytes
func(n int64)
Records the number of bytes processed in a single operation.

M

The M type is a type passed to a TestMain function to run the actual tests.
type M struct {
    // contains filtered or unexported fields
}

Methods

Run
func() int
Runs the tests. It returns an exit code to pass to os.Exit.

Functions

Short
func() bool
Reports whether the -test.short flag is set.
Verbose
func() bool
Reports whether the -test.v flag is set.
Testing
func() bool
Reports whether the current code is being run in a test. This will report true in programs created by “go test”, false in programs created by “go build”.
CoverMode
func() string
Reports what the test coverage mode is set to. The values are “set”, “count”, or “atomic”.

Examples

Basic Test

func TestAbs(t *testing.T) {
    got := abs(-1)
    if got != 1 {
        t.Errorf("abs(-1) = %d; want 1", got)
    }
}

Subtest

func TestFoo(t *testing.T) {
    t.Run("A=1", func(t *testing.T) {
        // test case 1
    })
    t.Run("A=2", func(t *testing.T) {
        // test case 2
    })
}

Table-Driven Test

func TestSum(t *testing.T) {
    tests := []struct {
        name string
        a, b int
        want int
    }{
        {"positive", 1, 2, 3},
        {"negative", -1, -2, -3},
        {"mixed", 1, -1, 0},
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := Sum(tt.a, tt.b)
            if got != tt.want {
                t.Errorf("Sum(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
            }
        })
    }
}

Benchmark (Modern Style with Loop)

func BenchmarkRandInt(b *testing.B) {
    for b.Loop() {
        rand.Int()
    }
}

Benchmark with Setup

func BenchmarkBigLen(b *testing.B) {
    big := NewBig()
    for b.Loop() {
        big.Len()
    }
}

Parallel Benchmark

func BenchmarkTemplateParallel(b *testing.B) {
    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
    b.RunParallel(func(pb *testing.PB) {
        var buf bytes.Buffer
        for pb.Next() {
            buf.Reset()
            templ.Execute(&buf, "World")
        }
    })
}

TestMain

func TestMain(m *testing.M) {
    // Setup code here
    flag.Parse()
    
    code := m.Run()
    
    // Teardown code here
    os.Exit(code)
}

Helper Function

func assertEqual(t *testing.T, got, want int) {
    t.Helper() // This line will be skipped in error messages
    if got != want {
        t.Errorf("got %d; want %d", got, want)
    }
}

func TestWithHelper(t *testing.T) {
    assertEqual(t, Sum(1, 2), 3)
}

Running Tests

# Run all tests
go test

# Run tests with verbose output
go test -v

# Run specific test
go test -run TestAbs

# Run tests in short mode
go test -short

# Run benchmarks
go test -bench .

# Run benchmarks with memory stats
go test -bench . -benchmem

Build docs developers (and LLMs) love