Go - Table Driven Test Helper Function

I've found so many good examples of the table driven test, but it seems no ones written about the next step of creating a helper test method to pass in the functions you want to test. So that this part of the code doesn't have to repeat for every function you want to test:

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

* UPDATED I have this code, now working (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)
        }
    }
}

But I was having trouble with the types or pointer or something for passing in a struct of test cases and the function to test in the table driven test loop. I'm getting this error in the code:

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

This was the closest I've found written about a go test helper function but it doesn't pass in a testcases struct or a function to test against: https://routley.io/tech/2017/11/05/intermediate-go-testing.html

Go TDD!

1 answer

  • answered 2018-02-13 00:24 Tim Heckman

    I think helper methods for table-driven tests aren't common because the "table" type will probably change between each test. This is because the table includes the inputs and expected outputs, and those changing result in a different type.

    The error you're getting is because you're trying to use one type where a different one is expected. You might be able to coerce curPairInputTestCases to a testCasesStructArray, but as soon as you make some changes to the struct type they will be incompatible.

    Small nitpick: []testCasesStruct is a slice and not an array.