go test command automates testing the packages named by import paths. It compiles test files, runs test functions, and reports results.
Overview
Testing is a first-class citizen in Go. Thego test command provides built-in support for unit tests, benchmarks, examples, and fuzz tests.
Basic Usage
Test Files
Test File Naming
Test files must:- End with
_test.go - Be in the same package directory
- Not start with
_or.
Test Modes
Local Directory Mode
Invoked without package arguments:- Compiles package in current directory
- Runs test binary immediately
- Caching is disabled
- Prints summary after completion
Package List Mode
Invoked with explicit package arguments:- Compiles and tests each listed package
- Results are cached
- Prints ‘ok’ for passing tests
- Shows full output for failures
Common Test Flags
Test Selection
Run only tests matching regexp
Skip tests matching regexp
Output Control
Verbose output - print all test names and results
Output test results as JSON
Test Execution
Run each test n times (default: 1)
Maximum number of tests to run in parallel (default: GOMAXPROCS)
Timeout for entire test execution (default: 10m)
Run in short mode - skip long-running testsIn test code:
Stop after first test failure
Coverage Flags
Enable coverage analysis
Write coverage profile to file
Set coverage mode
set: boolean (was this line executed?)count: count how many times each line executedatomic: like count, but correct for concurrent tests
Writing Tests
Basic Test Function
Table-Driven Tests
Testing Methods
t.Error / t.Errorf
t.Error / t.Errorf
Report error but continue test:
t.Fatal / t.Fatalf
t.Fatal / t.Fatalf
Report error and stop test immediately:
t.Log / t.Logf
t.Log / t.Logf
Print log output (only shown with -v or on failure):
t.Skip / t.Skipf
t.Skip / t.Skipf
Skip test:
t.Cleanup
t.Cleanup
Register cleanup function:
Benchmarks
Writing Benchmarks
Running Benchmarks
Examples
Writing Examples
Code Coverage
Coverage Options
Test Caching
Go caches successful test results to avoid unnecessary reruns.Cacheable Flags
Tests are cached when using only these flags:-benchtime-cpu-coverprofile-failfast-fullpath-list-outputdir-parallel-run-short-skip-timeout-v
Disabling Cache
Advanced Testing
Setup and Teardown
Parallel Tests
Using testdata Directory
Test Compilation
Compile Test Binary
Binary Flags
Compiled test binaries accept-test.* flags:
CI/CD Integration
GitHub Actions
.github/workflows/test.yml
Makefile
Troubleshooting
Tests are cached when they shouldn't be
Tests are cached when they shouldn't be
Tests timeout
Tests timeout
Race detector issues
Race detector issues
See Also
go Command
Overview of go command
Building
Building Go programs
Benchmarking
Performance testing