Home >Backend Development >Golang >How to Unit Test Custom Command Line Flag Validation in Go?
Validating Command Line Flags in Go Unit Tests
Consider the following code that uses command line flags to configure the format type:
<code class="go">// ... elided for brevity ...</code>
To ensure that the -format flag is set to an expected value, a unit test can be written. The flag.Var function can be employed to customize the processing of flags, allowing for validation and more control over the flag values.
Custom flag handling is achieved by implementing the Value interface:
<code class="go">type formatType string func (f *formatType) String() string { return fmt.Sprint(*f) } func (f *formatType) Set(value string) error { // Validation logic here }</code>
Applying this to the format flag:
<code class="go">var typeFlag formatType func init() { // ... elided for brevity ... flag.Var(&typeFlag, "format", "Format type") flag.Var(&typeFlag, "f", "Format type (shorthand)") }</code>
To unit test the custom flag validation, consider the following approach found in flag_test.go:
<code class="go">func TestCustomFlag(t *testing.T) { // Setup test environment origArgs := os.Args // Define custom flag type type myFlag int flag.Var((*myFlag)(nil), "customflag", "Custom flag") tests := []struct { origArgs []string expValue int expOutput string }{ // ... test cases ... } for _, test := range tests { os.Args = test.origArgs // Parse flags flag.Parse() // Check flag value if flagValue := flag.Lookup("customflag").Value.(myFlag); flagValue != test.expValue { t.Errorf("Expected %v, got %v", test.expValue, flagValue) } // Restore args os.Args = origArgs } }</code>
In summary, the flag.Var function allows for customization and validation of flag values, which can be unit tested following established patterns.
The above is the detailed content of How to Unit Test Custom Command Line Flag Validation in Go?. For more information, please follow other related articles on the PHP Chinese website!