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

How to Correctly Test Argument Passing in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 17:34:13850browse

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

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"}

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

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!

Statement:
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