Loading...
Loading...
This skill should be used when the user asks to "write Go unit tests", "add tests to a Go package", "use the testing package", "write table-driven tests in Go", or needs guidance on Go test patterns, subtests, benchmarks, and test helpers.
npx skill4agent add the-perfect-developer/the-perfect-opencode go-testingtestinggo test_test.gogo testfunc TestXxx(*testing.T)Xxxpackage mypackage
import "testing"
func TestAdd(t *testing.T) {
got := Add(2, 3)
if got != 5 {
t.Errorf("Add(2, 3) = %d; want 5", got)
}
}package mypackage_testpackage mypackage_test| Method | Behaviour |
|---|---|
| Marks failed, continues execution |
| Marks failed, continues execution |
| Marks failed, stops test immediately |
| Marks failed, stops test immediately |
| Marks failed without logging, continues |
| Marks failed without logging, stops immediately |
ErrorfErrorFatalfFatalt.Errorft.Fatalffunc TestDivide(t *testing.T) {
tests := []struct {
name string
a, b float64
want float64
wantErr bool
}{
{name: "positive", a: 10, b: 2, want: 5},
{name: "negative divisor", a: 10, b: -2, want: -5},
{name: "divide by zero", a: 10, b: 0, wantErr: true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := Divide(tc.a, tc.b)
if (err != nil) != tc.wantErr {
t.Fatalf("Divide(%v, %v) error = %v, wantErr %v", tc.a, tc.b, err, tc.wantErr)
}
if !tc.wantErr && got != tc.want {
t.Errorf("Divide(%v, %v) = %v; want %v", tc.a, tc.b, got, tc.want)
}
})
}
}t.Runt.Run(name, func(t *testing.T))TestParent/SubNamego test -run TestParent/SubNamefunc TestAPI(t *testing.T) {
server := startTestServer(t) // shared setup
t.Run("GET /users", func(t *testing.T) {
// ...
})
t.Run("POST /users", func(t *testing.T) {
// ...
})
// server is cleaned up after all subtests finish
}t.Parallel()func TestExpensive(t *testing.T) {
t.Parallel()
// ...
}for _, tc := range tests {
tc := tc // capture range variable (required before Go 1.22)
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
// use tc safely
})
}tc := tct.Cleanup(f func())func TestWithDB(t *testing.T) {
db := openTestDB(t)
t.Cleanup(func() { db.Close() })
// test body — db.Close is called automatically when test ends
}t.Cleanupdefert.Helper()func assertEqualInts(t *testing.T, got, want int) {
t.Helper() // makes error line point to the caller
if got != want {
t.Errorf("got %d; want %d", got, want)
}
}t.Helper()t.TempDir()func TestWriteFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.txt")
// write to path — dir is cleaned up automatically
}t.Setenv(key, value)func TestWithEnv(t *testing.T) {
t.Setenv("MY_CONFIG", "test-value")
// original value restored after test
}t.Skipt.Skipft.SkipNowfunc TestIntegration(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
// ...
}
func TestRequiresDocker(t *testing.T) {
if os.Getenv("DOCKER_HOST") == "" {
t.Skip("DOCKER_HOST not set")
}
// ...
}go testfunc ExampleAdd() {
fmt.Println(Add(1, 2))
// Output: 3
}// Output:// Unordered output:func Example() { ... } // package example
func ExampleAdd() { ... } // function Add
func ExampleCalc() { ... } // type Calc
func ExampleCalc_Add() { ... } // method Calc.Add
func ExampleAdd_second() { ... } // second example for Add (suffix starts lowercase)TestMain_test.gofunc TestMain(m *testing.M) {
// setup
code := m.Run()
// teardown
os.Exit(code)
}TestMaint.Cleanup# Run all tests in the current module
go test ./...
# Run with verbose output
go test -v ./...
# Run tests matching a pattern (regexp)
go test -run TestAdd ./...
# Run a specific subtest
go test -run TestDivide/divide_by_zero ./...
# Run with race detector
go test -race ./...
# Run with coverage
go test -cover ./...
# Generate HTML coverage report
go test -coverprofile=coverage.out ./... && go tool cover -html=coverage.out
# Skip slow tests
go test -short ./...
# Set test timeout
go test -timeout 30s ./...
# Run benchmarks
go test -bench=. ./...
# Run benchmarks with memory allocation stats
go test -bench=. -benchmem ./...testing.T| Method | Purpose |
|---|---|
| Create named subtest |
| Mark test as parallel |
| Mark as helper function |
| Register teardown function |
| Create auto-cleaned temp directory |
| Set env var, auto-restored after test |
| Change working dir, auto-restored |
| Context canceled before cleanup runs |
| Log (shown on failure or with |
| Log formatted |
| Fail + log, continue |
| Fail + log formatted, continue |
| Fail + log, stop |
| Fail + log formatted, stop |
| Skip + log, stop |
| Skip + log formatted, stop |
| Return full test name |
| Reports whether test has failed |
| Returns test deadline from |
references/benchmarks-and-fuzzing.mdtesting.Bb.Loop()testing.FTestMainAllocsPerRun