Go - 表驱动的测试助手功能

时间:2018-02-13 00:24:12

标签: unit-testing go

我发现了很多关于表驱动测试的好例子,但似乎没有人写下创建辅助测试方法的下一步来传递你想要测试的函数。因此,对于您要测试的每个函数,代码的这一部分不必重复:

func TestFib(t *testing.T) {
  for _, tt := range fibTests {
    actual := Fib(tt.n)
    if actual != tt.expected {
      t.Errorf("Fib(%d): expected %d, actual %d", tt.n, tt.expected, actual)
    }
  }
}
// from: https://medium.com/@matryer/5-simple-tips-and-tricks-for-writing-unit-tests-in-golang-619653f90742

*更新我有这段代码,正在运行(https://gist.github.com/mikeumus/a97da2d65bfa4f5b92e13177f6a88922):

type testCasesStruct []struct {
    n        string
    expected bool
}
type valUserInType func(string) bool

var curPairInputTestCases = []struct {
n        string
expected bool
}{
    {"1/d", false},
    // continued test cases...
}

func TestGoPolSuite(t *testing.T) {
    methodTester(t, validateCurPairInput, curPairInputTestCases)
}

func methodTester(t *testing.T, testingMethod valUserInType, testCases testCasesStruct) {
    t.Helper()
    for _, tt := range testCases {
        actual := testingMethod(tt.n)
        if actual != tt.expected {
            t.Errorf("\n%v(%v)\n expected: %v\n actual: %v\n", testingMethod, tt.n, tt.expected, actual)
        }
    }
}

但是我遇到了类型或指针或者用于传递测试用例结构和在表驱动测试循环中测试的函数的问题。我在代码中收到此错误:

<击> cannot use curPairInputTestCases (type []struct { n string; expected bool }) as type testCasesStructArray in argument to methodTester

这是我发现的关于go测试辅助函数的最接近的函数,但它没有传入testcases结构或函数来测试:https://routley.io/tech/2017/11/05/intermediate-go-testing.html

转到TDD!

1 个答案:

答案 0 :(得分:1)

我认为表驱动测试的辅助方法并不常见,因为“table”类型可能会在每次测试之间发生变化。这是因为该表包含输入和预期输出,以及那些以不同类型更改结果的表。

您获得的错误是因为您尝试使用一种预期不同的类型。您可以将curPairInputTestCases强制转换为testCasesStructArray,但只要对结构类型进行一些更改,它们就会不兼容。

小挑剔:[]testCasesStruct是切片而不是数组。