Home > Backend Development > Golang > Can golang variadic parameters be used in unit testing?

Can golang variadic parameters be used in unit testing?

PHPz
Release: 2024-04-29 18:09:02
Original
573 people have browsed it

Variadic parameters in the Go language allow functions to receive a variable number of parameters, using the ... syntax. However, unit tests cannot pass variadic parameters directly. You can use reflection to create a test helper function and call the function dynamically using the reflect.ValueOf(sumNumbers).CallSlice(reflect.ValueOf(tt.args)) method.

Can golang variadic parameters be used in unit testing?

Variadic parameters in the Go language

Variadic parameters allow a function to receive a variable number of parameters. In Go, variadic arguments use the ... syntax.

Practical combat

The following code demonstrates the use of variable parameters:

func sumNumbers(args ...int) int {
    sum := 0
    for _, v := range args {
        sum += v
    }
    return sum
}

func main() {
    // 传递一个参数
    result := sumNumbers(10)
    fmt.Println(result) // 输出:10

    // 传递多个参数
    result = sumNumbers(10, 20, 30)
    fmt.Println(result) // 输出:60
}
Copy after login

Variable parameters in unit tests

Variable parameters cannot be passed directly in unit tests. This is because the Go language testing framework does not support them.

However, we can use reflection to dynamically call functions with variable parameters. The following code demonstrates how to create a test helper function for this:

func TestSumNumbers(t *testing.T) {
    tests := []struct {
        args []int
        want int
    }{
        {[]int{10}, 10},
        {[]int{10, 20}, 30},
    }

    for _, tt := range tests {
        t.Run(fmt.Sprintf("%v", tt.args), func(t *testing.T) {
            got := reflect.ValueOf(sumNumbers).CallSlice(reflect.ValueOf(tt.args))
            if got.Int() != tt.want {
                t.Errorf("sumNumbers(%v) = %v, want %v", tt.args, got.Int(), tt.want)
            }
        })
    }
}
Copy after login

This helper function dynamically calls the sumNumbers function using the CallSlice method, passing a []int slice as parameter.

The above is the detailed content of Can golang variadic parameters be used in unit testing?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template