Testing
52 articles
Fix: "no test files" in Go
The "no test files" error occurs because Go cannot find any files matching the `_test.go` pattern in the current directory or its subdirectories.
Fix: Tests Pass Locally but Fail in CI
Fix local vs CI test failures by aligning GODEBUG settings and CGO_ENABLED flags in your go.mod or CI configuration.
Fuzzing in Go
Enable Go fuzzing with the -asan flag and run tests using -test.fuzz to automatically detect memory errors and logic bugs.
Go Commands Cheat Sheet: build, run, test, get, mod, vet, fmt, and More
Essential Go commands for building, running, testing, and maintaining code.
How to Design for Testability with DI in Go
Use interfaces and constructor injection to swap real dependencies with mocks for isolated, fast Go tests.
How to Detect Goroutine Leaks with goleak in Tests
Use the `goleak` package to automatically detect and report any goroutines that remain running after your test function completes.
How to Interpret Benchmark Results in Go
Interpret Go benchmarks by checking ns/op for speed and B/op/allocs/op for memory efficiency, where lower values indicate better performance.
How to Measure Test Coverage in Go
You measure test coverage in Go by running the `go test` command with the `-cover` flag to get a percentage, or `-coverprofile` to generate a detailed report file for analysis.
How to Mock Database Calls in Go
Mock database calls in Go by defining an interface and implementing a fake struct that returns controlled data during tests.
How to Mock HTTP Calls in Go (httptest)
Mock HTTP calls in Go by using net/http/httptest to create in-memory servers and recorders for testing handlers without network I/O.
How to Mock Interfaces in Go
Create a struct that implements the interface methods and inject it to replace the real dependency during testing.
How to Mock time.Now in Go Tests
Replace time.Now with a variable function to inject fixed times in Go tests.
How to Run Tests in Go (go test Command)
Run Go tests using the go test command with optional flags for verbose output or specific test selection.
How to Skip Tests Conditionally in Go
Skip Go tests conditionally using t.Skip() or build tags to exclude them on specific platforms.
How to Suppress or Filter Logs in Tests
Suppress Go test logs by redirecting os.Stdout to io.Discard or using t.Log for conditional output.
How to Test Database Code in Go (Integration Testing)
Run Go database integration tests using the testing package with in-memory databases and cleanup functions to verify real SQL interactions.
How to Test gRPC Services in Go
Test gRPC services in Go by spinning up an HTTP/2 test server and connecting a gRPC client to it.
How to Test Private (Unexported) Functions in Go
Test private Go functions by creating a test file in the same package with the _test suffix to access unexported identifiers.
How to Use Build Tags for Integration Tests
Add //go:build integration to test files and run go test -tags=integration to execute them.
How to Use go build and Its Flags
Use go build to compile Go code into an executable, with flags like -o for output naming and -race for debugging.
How to Use gomock for Generating Mock Objects
Gomock is not available in the provided Go standard library source code and must be installed separately to generate mock objects.
How to Use go test -coverprofile and go tool cover
Generate a Go test coverage profile with go test -coverprofile and visualize it using go tool cover -html or -func.
How to Use mockery for Generating Mocks in Go
Generate Go interface mocks instantly using the mockery CLI command with the --name flag to specify the target interface.
How to Use mockgen for Generating Mock Implementations
Use `mockgen` to generate mock implementations by defining your target interface in Go code and running the tool with the interface name and destination package as arguments.
How to Use Table-Driven Tests in Go
Define a slice of test cases and loop through them with t.Run to validate multiple inputs in a single Go test function.
How to Use t.Cleanup for Test Cleanup
Register a cleanup function with t.Cleanup to ensure resources are released after a test completes.
How to Use Testcontainers for Integration Tests in Go
Use the testcontainers-go library to start real Docker containers for integration testing by defining a container request and running it with the GenericContainer function.
How to Use testcontainers-go for Docker-Based Integration Tests
Use testcontainers-go to automate spinning up Docker containers for integration tests, handling lifecycle management and port mapping automatically.
How to Use Test Fixtures and testdata in Go
Store test data in a `testdata` directory and load it using `os.ReadFile` with `filepath.Join` for portable Go tests.
How to Use Testify for Assertions and Mocking in Go
Use Testify's assert package for readable checks and the mock package to simulate dependencies in Go tests.
How to use testing package
Write Test functions with *testing.T arguments and run them using go test to automate verification of your Go code.
How to Use t.Helper to Improve Test Output
Call t.Helper() in test helper functions to make failure stack traces point to the calling code instead of the helper.
How to Use the testing/fstest Package for File System Tests
Use testing/fstest to create in-memory file systems for safe, isolated unit tests without touching the real disk.
How to Use the testing/quick Package for Fuzz-Like Tests
Use testing.F and f.Fuzz for fuzzing in Go, not the deprecated testing/quick package.
How to Use t.Parallel for Parallel Tests in Go
Use `t.Parallel()` to mark a test function as runnable concurrently with other parallel tests, allowing them to execute simultaneously on available CPU cores rather than sequentially.
How to Use t.Run for Subtests in Go
Use `t.Run(name, func(t *testing.T))` to define subtests within a parent test function, allowing you to run multiple test cases in parallel while keeping the test output organized by name.
How to Use t.Setenv for Environment Variables in Tests
Use t.Setenv to temporarily set environment variables in Go tests with automatic cleanup.
How to Write Benchmarks in Go with testing.B
Write a function accepting *testing.B that loops b.N times around your code to measure performance.
How to Write Example Functions (Testable Examples) in Go
Write a function starting with Example followed by the target name and include an Output comment to create a testable Go example.
How to Write Fuzz Tests in Go (Go 1.18+)
Write a Fuzz function with *testing.F, add seed inputs, and run with go test -fuzz to automatically find bugs with random data.
How to Write Integration Tests in Go
Write Go integration tests by creating Test functions in _test.go files that verify interactions between components or external systems.
How to Write Table-Driven Tests Idiomatically in Go
Write Go table-driven tests by defining a slice of test cases with inputs and expected outputs, then looping over them in a test function to verify behavior.
How to Write Tests for CLI Applications in Go
Test Go CLI apps by injecting arguments into os.Args and calling main() within a testing function.
How to write unit tests
Create a _test.go file with Test functions and run go test to verify your code logic.
How to Write Unit Tests in Go with testing Package
Write test functions in *_test.go files using the testing package and run them with go test.
Integration tests
Run integration tests by building with coverage flags, executing with GOCOVERDIR, and analyzing results with go tool covdata.
Mock interfaces
Mock interfaces in Go by creating a struct that implements the interface methods to control test behavior and isolate dependencies.
Table-driven tests
Table-driven tests use a slice of structs to define multiple test cases and iterate over them in a single function.
Test coverage
Run go test with the -cover flag to measure code coverage and generate a report.
Test HTTP handlers
Test HTTP handlers by using httptest.NewRecorder and httptest.NewRequest to simulate requests and verify responses.
Test Organization Patterns in Go: _test.go, external test packages
Use internal tests for unit testing unexported code and external tests for integration testing exported APIs.
Using testify
Use testify's assert or require functions to write clear, concise assertions in your Go unit tests.