Home > Backend Development > Golang > How to Effectively Test Argument Passing in Golang Functions?

How to Effectively Test Argument Passing in Golang Functions?

Susan Sarandon
Release: 2024-12-08 17:52:10
Original
419 people have browsed it

How to Effectively Test Argument Passing in Golang Functions?

Testing the Passing of Arguments in Golang

In Golang, passing arguments to a function is a common way to provide inputs. Testing the correctness of argument passing is crucial to ensure the reliability of your code.

The Challenge

Consider the following code snippet:

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
}
Copy after login

When passing the argument -user=bla to this program, it correctly prints "Your username is 'bla'." The challenge is to create a test that verifies this behavior without having to manually build and run the code each time.

The Attempt

One might尝试使用 os.Args to provide the argument in a 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)
    }
}
Copy after login

However, when running this test, the result is:

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
Copy after login

The Solution

The issue is that os.Args is a global variable, so the initial value of ["args"] is overwritten by the test, affecting other parts of the program. To resolve this, we can preserve the original value and restore it after the test:

oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"cmd", "-user=bla"}

// ...
Copy after login

The above is the detailed content of How to Effectively Test Argument Passing in Golang Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template