Testing Command-Line Arguments in Go Unit Tests
In your question, you mention an issue with using command-line flags in Go unit tests. You have a modular application with tests that use different sets of application modules, some of which are tuned through command-line flags. However, when you run the tests with custom command-line flags, you get an error stating that the flag is not defined.
The underlying issue is that the test executable applies all the command-line parameters unless one or more of them is ignored within it. In your case, you have multiple tests, and some of them use the custom flag while others do not.
To resolve this issue, you have two options:
go test -test.v ./testfile1_test.go -gamedir.custom=c:/resources go test -test.v ./testfile2_test.go
var customPath string func init() { flag.StringVar(&customPath, "gamedir.custom", "", "Custom game resources directory") } func TestFunc(t *testing.T) { if testing.Short() { return } t.Skip("Skipping this test as it uses `-gamedir.custom` flag") }
The testing.Short() check is used to determine if the test is being run in short mode, which is usually the case when running all tests simultaneously. If the test is being run in short mode, it will be skipped. Otherwise, the test will be skipped because the -gamedir.custom flag is not being used.
The above is the detailed content of How Can I Effectively Test Command-Line Arguments in Go Unit Tests?. For more information, please follow other related articles on the PHP Chinese website!