如何在 Golang 中测试参数的传递? [英] How to test the passing of arguments in Golang?

查看:13
本文介绍了如何在 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"

显示已传递的用户名.

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

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"} 应该可以解决您的问题.您可以从他们正在执行的标准包中查看 flag test类似的东西.

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 }()

这在其他测试中可能很有用,例如,检查调用 go test 时传递的真实参数.

This might be useful where other tests are, for example, examining the real arguments passed when evoking go test.

这篇关于如何在 Golang 中测试参数的传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆