doudieheng5322
2015-11-15 18:25
浏览 225
已采纳

如何在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

results in:

Your username is "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.


Attempt

Running the following 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)
    }
}

results in:

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

Problem

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

图片转代码服务由CSDN问答提供 功能建议

 包主程序
 
import(
“标志” 
“ fmt” 
)\  n 
func main(){
 passArguments()
} 
 
func passArguments()string {
 username:= flag.String(“ user”,“ root”,“此服务器的用户名”)
  flag.Parse()
 fmt.Printf(“您的用户名是%q。”,*用户名)
 
 usernameToString:= *用户名
返回usernameToString 
} 
   \  n 
 

将参数传递给已编译的代码:

./ args -user = bla

结果为:

您的用户名为“ bla”

显示已传递的用户名。


目标:为了防止需要每次手动构建和运行代码来测试代码,目的是 编写能够测试参数传递的测试。


尝试

运行以下测试:

 程序包main 
 
import(
“ os” 
“ testing” 
)
 
func TestArgs(t * testing。  T){
预期:=“ bla” 
 os.Args = [] string {“-user = bla”} 
 
实际:= passArguments()
 
如果实际!=预期{
  t.Errorf(“测试失败,预期:'%s',得到:'%s'”,预期,实际)
} 
} 
   
 
 

结果为:

 您的用户名是“ root”。您的用户名是“ root”。---失败:TestArgs(0.00s)
 args_test.go:15:测试 失败,预期:'bla',得到:'root'
FAIL 
coverage:语句的87.5%
FAIL工具0.008s 
   
 
 

问题

看起来 os.Args = [] string {“-user = bla 将此参数赋值给函数,因为结果是 root 而不是 bla

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulao2128 2015-11-15 18:59
    已采纳

    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.

    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.

    打赏 评论

相关推荐 更多相似问题