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
}
将参数传递给编译后的代码:
./args -user=bla
结果是:
Your username is "bla"
显示已传递的用户名。
目的:为了防止每次都需要手动构建和运行代码来测试代码,目的是编写一个能够测试参数传递的测试。
试图
运行以下测试:
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
慕雪6442864
相关分类