Go Tests "flag provided but not defined" - Fix in CI
The compiled test binary was passed a flag it does not recognize. go test forwards anything after -args (and unknown flags) to the binary, which rejects flags it never registered.
What this error means
A go test invocation fails immediately with flag provided but not defined: -myflag, followed by the test binary’s usage. No tests run because flag parsing fails at startup.
flag provided but not defined: -env
Usage of /tmp/go-build/store.test:
-test.run string
...
FAIL github.com/org/app/store 0.002sCommon causes
A custom flag passed but never registered
A flag like -env=ci was passed to the test binary, but no flag.String("env", ...) declares it, so parsing rejects it.
A flag declared after flag.Parse runs
Test flags must be registered (typically in TestMain or a package var) before the binary parses them. Declaring one too late means it is not defined when parsing happens.
A go test flag in the wrong position
Built-in flags must use the -test. form or appear before -args; a misplaced flag is treated as one the binary does not define.
How to fix it
Register the custom flag
Declare the flag as a package-level var so it exists when the test binary parses arguments.
var env = flag.String("env", "local", "target environment")
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}Pass custom flags after -args
Separate go test’s own flags from flags meant for the test binary with -args.
go test ./store -run TestSync -args -env=ciHow to prevent it
- Register every custom test flag as a package-level
flagvar. - Parse flags in
TestMainbeforem.Run(). - Put binary-specific flags after
-argsin the command.