Home > Backend Development > Golang > How to Correctly Test Argument Passing in Go?

How to Correctly Test Argument Passing in Go?

Mary-Kate Olsen
Release: 2024-12-15 06:48:14
Original
869 people have browsed it

How to Correctly Test Argument Passing in Go?

Testing Argument Passing in Golang

Consider the following code:

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

We pass an argument to the compiled code using the command:

./args -user=bla
Copy after login

This displays the following output:

Your username is "bla"
Copy after login

Testing Approach

To avoid manual compilation and execution, we aim to write a test that verifies argument passing. We create a test function:

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

Problem

When we run the test, we encounter an unexpected outcome:

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 argument "bla" is not passed to the function, resulting in "root" as the displayed username.

Solution

The issue lies in setting os.Args. The first argument in os.Args is the path to the executable itself. To fix this, we modify it as follows:

os.Args = []string{"cmd", "-user=bla"}
Copy after login

Additionally, it's good practice to save the original os.Args state and restore it after the test for other tests that rely on the correct arguments.

The above is the detailed content of How to Correctly Test Argument Passing in Go?. 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