Accessing Command Line Arguments in Go Tests
In Go tests, the main function is not executed, raising the question of how command line arguments can be processed. While using the flags package to check for arguments in each test or function is an option, it requires repetitive code insertion, which is undesirable.
Environmental configurations are typically stored in environment variables for convenient access. However, for scenarios where relying on environment variables is not feasible, global variables like so can be used:
var envSetting = os.Getenv("TEST_ENV")
Alternatively, for mandatory flag usage, initialization code can be placed within an init() function:
func init() { flags.Parse() myEnv = *envFlag // ... }
This allows for accessing command line arguments by simply setting the associated environment variable or invoking the test with the appropriate flags.
The above is the detailed content of How Can I Access Command Line Arguments within Go Tests?. For more information, please follow other related articles on the PHP Chinese website!