Home >Backend Development >Golang >How to Effectively Test Argument Passing in Golang Functions?
Testing the Passing of Arguments in Golang
In Golang, passing arguments to a function is a common way to provide inputs. Testing the correctness of argument passing is crucial to ensure the reliability of your code.
The Challenge
Consider the following code snippet:
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 }
When passing the argument -user=bla to this program, it correctly prints "Your username is 'bla'." The challenge is to create a test that verifies this behavior without having to manually build and run the code each time.
The Attempt
One might尝试使用 os.Args to provide the argument in a test:
package main import ( "os" "testing" ) 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) } }
However, when running this test, the result is:
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 Solution
The issue is that os.Args is a global variable, so the initial value of ["args"] is overwritten by the test, affecting other parts of the program. To resolve this, we can preserve the original value and restore it after the test:
oldArgs := os.Args defer func() { os.Args = oldArgs }() os.Args = []string{"cmd", "-user=bla"} // ...
The above is the detailed content of How to Effectively Test Argument Passing in Golang Functions?. For more information, please follow other related articles on the PHP Chinese website!