如何在Golang中测试参数的传递? [英] How to test the passing of arguments in Golang?
问题描述
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
}
将参数传递给已编译的代码:
Passing an argument to the compiled code:
./ args -user = bla
结果:
您的用户名是 bla
显示已通过的用户名。
the username that has been passed is displayed.
目标:为了防止需要每次手动构建和运行代码是时候测试代码了,目的是编写一个能够测试参数传递的测试。
Aim: in order to prevent that the code needs to be build and run manually every time to test the code the aim is to write a test that is able to test the passing of arguments.
尝试
运行以下测试:
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)
}
}
结果:
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
问题
看起来 os.Args = [] string {-user = bla
不能将此参数传递给函数,因为结果是 root
而不是 bla
It looks like that the os.Args = []string{"-user=bla
is not able to pass this argument to the function as the outcome is root
instead of bla
推荐答案
根据我的评论, os.Args
中的第一个值是可执行文件本身的(路径),因此 os.Args = [] string { cmd, -user = bla}
应该可以解决您的问题。您可以从标准套件中查看标志测试
Per my comment, the very first value in os.Args
is a (path to) executable itself, so os.Args = []string{"cmd", "-user=bla"}
should fix your issue. You can take a look at flag test from the standard package where they're doing something similar.
另外,由于 os.Args
是全局变量,所以可能是个好主意保持测试前的状态,并在测试后恢复状态。类似于链接的测试:
Also, as os.Args
is a "global variable", it might be a good idea to keep the state from before the test and restore it after. Similarly to the linked test:
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
这在其他测试(例如检查何时传递的真实参数)时可能有用唤起去测试
。
This might be useful where other tests are, for example, examining the real arguments passed when evoking go test
.
这篇关于如何在Golang中测试参数的传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!