将函数传递给帮助程序方法



是否可以在 Go 中迭代一组函数?

我的单元测试文件中有这个辅助方法:

func helper(t *testing.T, f func(string) bool, stringArray []string, expected bool) {
for _, input := range stringArray {
if f(input) != expected {
t.Errorf("Expected '%v' for string: %v", !expected, input)
}
}
}

而不是像这样复制/粘贴一行并更改第二个 peramiter:

func Test_isUnique(t *testing.T) {
var valid = []string{"", "b", "ab", "acd", "asdfjkl", "aA"}
var invalid = []string{"aa", "avva", "aaa", "asdfweryhfda", "asdfjkal"}
helper(t, funcA, valid, true)
helper(t, funcB, invalid, false)
helper(t, funcC, valid, true)
helper(t, funcD, invalid, false)
helper(t, funcE, valid, true)
helper(t, funcF, invalid, false)
helper(t, funcG, valid, true)
helper(t, funcH, invalid, false)
}

相反,我想知道这里是否有一个 for 选项可以将其简化为 4 行主体函数

for f in [funcA, funcB, funcB, funcC, funcD, etc]: // Fix this
helper(t, f, valid, true)
helper(t, f, invalid, false)

原谅 python/go 的混合:)

是的,这是可能的。 例如,您可以覆盖任何切片,包括元素类型为函数类型的切片。只需将您的函数放入一个切片中:

fs := []func(string) bool{funcA, funcB, funcC, funcD, ...}
for _, f := range fs {
helper(t, f, valid, true)
helper(t, f, invalid, false)
}

同样,对于您要实现的目标,表驱动测试可能更合适。请查看 Go Wiki:表驱动测试,以及 Go 博客:使用子测试和子基准测试。

惯用的方法是使用表驱动测试:

func TestMyFunction(t *testing.T) {
valid := []string{"", "b", "ab", "acd", "asdfjkl", "aA"}
cases := []struct{
name string,
f func(string) bool
input []string
expected bool
}{
{
"Test func a",
funcA,
valid,
true
},
// Other test cases
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
helper(t, tc.func, tc.input, tc.expected)
})
}
}

作为旁注:您实际上可以使用帮助程序函数显式标记帮助程序函数。这可确保从运行测试时打印的行信息中排除帮助程序函数:

func helper(t *testing.T) {
t.Helper()
// Helper function code
}

最新更新