How to Fix go test flag: flag provided but not defined

Go test flag: flag provided but not defined error occurs when you “provide a command-line flag to go test that it doesn’t recognize.” This error message tells us that a flag has not been defined. The error can occur if you use an “outdated version of Go.”

To fix this error, you can use the var _ = func() bool { testing.Init(); return true }() as a possible workaround, which would call test initialization before the application one.

Diagram of the error

Diagram of the error

You can view the list of flags supported by go test by running:

go help testflag

If you are trying to pass flags to the test binary itself, rather than go test, you need to use the -args flag to separate the flags intended for the test binary.

Here’s an example:

go test -v -args -my_custom_flag=value

In this example, -v is a flag for the go test, while -my_custom_flag is a flag for the test binary.

The -args flag tells the go test that the following flags should be passed to the test binary.

Ensure you use the correct flags and syntax when running the go test.

You can also upgrade to the latest version of Go to resolve the error if any solutions don’t work.

That’s it.