Skip to content

Instantly share code, notes, and snippets.

@eujoy
Created June 10, 2020 12:29
Show Gist options
  • Save eujoy/723758a13971922fc9f40993679d85fb to your computer and use it in GitHub Desktop.
Save eujoy/723758a13971922fc9f40993679d85fb to your computer and use it in GitHub Desktop.
Example of creating unit tests using the table driven approach
func TestWithFunctions(t *testing.T) {
type setupFunc func(t *testing.T, <other options>)
type checkFunc func(t *testing.T, <other options>)
testCases := map[string]struct{
setupFn setupFunc
checkFn checkFunc
wantResult interface{}
wantError error
}{
"Name of the test": {
setupFn: func(t *testing.T, <other options>) {
// Perform all the setup for this case
},
checkFn: func(t *testing.T, actualResult, wantResult interface{}, actualError, wantError error, <other options>) {
if !reflect.DeepEqual(wantResult, actualResult) {
t.Errorf("Expected to get %v as result but got %v", wantResult, actualResult)
}
if wantError == actualError {
t.Errorf("Expected to get %v as error but got %v", wantError, actualError)
}
// Perform the rest checks you need for this case...
},
wantResult: interface{},
wantError: nil,
},
// Rest of test cases...
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
tc.setupFn(t, <rest of args>)
actualResult, actualError := <the function to call>(...)
tc.checkFn(t, actualResult, tc.wantResult, actualError, tc.wantError)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment