Testing Argument Passing in Golang
In Golang, arguments can be passed to functions using flags. To test the passing of arguments, a test can be written that simulates the passing of command-line arguments.
The Problem
When running the following test:
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) } }
the test fails with an error message indicating that the expected result ("bla") does not match the actual result ("root").
The Solution
The problem arises because the first value in os.Args is the path to the executable itself. To fix this, the os.Args slice should be updated to include both the executable and the argument:
os.Args = []string{"cmd", "-user=bla"}
Additionally, os.Args is a global variable, so it is recommended to save the original state and restore it after the test to prevent interference with other tests:
oldArgs := os.Args defer func() { os.Args = oldArgs }()
The above is the detailed content of How to Correctly Test Argument Passing in Golang?. For more information, please follow other related articles on the PHP Chinese website!