How to test the passing of arguments in Golang?

后端 未结 1 1478
心在旅途
心在旅途 2021-01-01 20:43
package main

import (
    \"flag\"
    \"fmt\"
)

func main() {
    passArguments()
}

func passArguments() string {
    username := flag.String(\"user\", \"root\",         


        
相关标签:
1条回答
  • 2021-01-01 21:28

    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.

    0 讨论(0)
提交回复
热议问题