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