Home >Backend Development >Golang >How to Correctly Test Argument Passing in Go?
Testing Argument Passing in Golang
Consider the following code:
package main import ( "flag" "fmt" ) func main() { passArguments() } func passArguments() string { username := flag.String("user", "root", "Username for this server") flag.Parse() fmt.Printf("Your username is %q.", *username) usernameToString := *username return usernameToString }
We pass an argument to the compiled code using the command:
./args -user=bla
This displays the following output:
Your username is "bla"
Testing Approach
To avoid manual compilation and execution, we aim to write a test that verifies argument passing. We create a test function:
func TestArgs(t *testing.T) { expected := "bla" os.Args = []string{"-user=bla"} actual := passArguments() if actual != expected { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } }
Problem
When we run the test, we encounter an unexpected outcome:
Your username is "root".Your username is "root".--- FAIL: TestArgs (0.00s) args_test.go:15: Test failed, expected: 'bla', got: 'root' FAIL coverage: 87.5% of statements FAIL tool 0.008s
The argument "bla" is not passed to the function, resulting in "root" as the displayed username.
Solution
The issue lies in setting os.Args. The first argument in os.Args is the path to the executable itself. To fix this, we modify it as follows:
os.Args = []string{"cmd", "-user=bla"}
Additionally, it's good practice to save the original os.Args state and restore it after the test for other tests that rely on the correct arguments.
The above is the detailed content of How to Correctly Test Argument Passing in Go?. For more information, please follow other related articles on the PHP Chinese website!