Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

testing - 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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...