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

How to Correctly Test Argument Passing in Golang?

Susan Sarandon
Release: 2024-12-07 17:34:13
Original
865 people have browsed it

How to Correctly Test Argument Passing in Golang?

Testing Argument Passing in Golang

In Golang, arguments can be passed to functions using flags. To test the passing of arguments, a test can be written that simulates the passing of command-line arguments.

The Problem

When running the following test:

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

the test fails with an error message indicating that the expected result ("bla") does not match the actual result ("root").

The Solution

The problem arises because the first value in os.Args is the path to the executable itself. To fix this, the os.Args slice should be updated to include both the executable and the argument:

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

Additionally, os.Args is a global variable, so it is recommended to save the original state and restore it after the test to prevent interference with other tests:

oldArgs := os.Args
defer func() { os.Args = oldArgs }()
Copy after login

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