Created
June 10, 2020 12:29
-
-
Save eujoy/723758a13971922fc9f40993679d85fb to your computer and use it in GitHub Desktop.
Example of creating unit tests using the table driven approach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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