Go "build failed" loading test package imports - Fix in CI
By Kaveh Alemi·Latchkey
Before running tests, Go loads and compiles the test package and everything it imports. A missing or wrong import there fails the load before any test runs.
What this error means
A run fails with cannot load package or [build failed] pointing at an import in a _test.go file. It means a test file imports something not provided, often a helper module not required.
go
pkg_test.go:7:2: cannot find module providing package github.com/stretchr/testify/assert;
to add it: go get github.com/stretchr/testify/assert
FAIL example.com/app/pkg [build failed]
Diagnose it: environment first
Terminal
go version
go env GOOS GOARCH CGO_ENABLED GOFLAGS GOPRIVATE GOPROXY
go mod verify
Common causes
Test-only dependency not required
A test imports a package (e.g. a test helper or assertion library) that go.mod does not require.
Wrong import path in a test file
A _test.go file imports a misspelled or moved path that does not resolve.
How to fix it
Add the test dependency
Run go mod tidy so test-only imports get require directives.
Commit go.mod and go.sum.
Terminal
go mod tidy
go test ./...
Fix the import path
Correct the import path in the test file to the real module path.
Terminal
go test -run=^$ ./...
How to prevent it
Run go mod tidy so test-only deps are recorded.
Keep test imports correct and module-qualified.
Compile tests in CI before running them.
Frequently asked questions
What causes Go "build failed" loading test package imports?
There are 2 common causes: test-only dependency not required and wrong import path in a test file. A test imports a package (e.g.
How do I fix Go "build failed" loading test package imports?
There are 2 fixes depending on which cause you have: add the test dependency and fix the import path. Work through them in order, since the first is the most common.
What does Go "build failed" loading test package imports actually mean?
A run fails with cannot load package or [build failed] pointing at an import in a _test.go file.
How do I stop Go "build failed" loading test package imports happening again?
Run go mod tidy so test-only deps are recorded. The prevention section lists 3 changes that keep it from recurring.