Skip to content

Latest commit

 

History

History

golang

GO Testing Cheatsheet

Unit Tests

Action Command Notes
Run tests in directory go test .
Run tests in directory tree go test ./...
Run tests matching regex go test ./... --run=NameOfTest
Run tests in specific file go test ./file_test.go ./file.go Include the file the test depends on for compilation.
Clean test cache go clean --testcache

Code Coverage

Remember: the only absolute conclusion that can be made is that code with zero coverage isn't unit tested at all. Code coverage does not guarantee the unit tests themselves are accurate and/or comprehensive.

Action Command Notes
See basic summary go test ./... --cover
Save report to text file go test ./... --coverprofile=coverage.out It's community convention to use the .out file extension for test results.
See summary of a saved report go tool cover --func=coverage.out
See details of a saved report go tool cover --html=coverage.out

Generate and View Code Coverage Heatmap

  1. Generate and save coverage report with frequency information: go test ./... --covermode=count --coverprofile=coverage.out.
  2. See details of the saved report: go tool cover --html=coverage.out.

Benchmark Tests

Beware high P-Values (wikipedia); benchmark results with a p-value greater than 0.05 are probably useless.

Action Command Notes
Run benchmarks in directory go test . --bench=. Also runs unit tests in directory.
Run benchmarks in directory tree go test ./... --bench=. Also runs unit tests in directory tree.
Run only benchmarks in directory tree go test ./... --run=^$ --bench=. Works by using a regex that matches nothing.
Run benchmarks matching regex go test ./... --bench=NameOfTest
Run benchmarks matching regex for 20 seconds go test ./... --bench=NameOfTest --benchtime=20s Increasing the test duration is usually the best way to reduce p-values for long-running functions.
Run benchmarks matching regex 10 times go test ./... --bench=NameOfTest --count=10 Increasing iterations is usually the best way to reduce p-values for short-running functions.

Comparing Benchmarks

  1. Install Russ Cox's benchstat utility: go get golang.org/x/perf/cmd/benchstat.
  2. Run the benchmark saving the results to a text file: go test ./... --bench=NameOfTest --count=10 > original.txt.
  3. Make your changes to the function under benchmark testing.
  4. Re-run the same benchmark saving the results to a different text file: go test ./... --bench=NameOfTest --count=10 > refactor.txt.
  5. Compare using the benchstat util: benchstat original.txt refactor.txt.

Additional Reading

Unit Testing

Code Coverage

Benchmark Testing