Skip to content

Instantly share code, notes, and snippets.

@nullren
Created May 29, 2020 16:00
Show Gist options
  • Save nullren/2dc79c167195a964118919e28ba679bf to your computer and use it in GitHub Desktop.
Save nullren/2dc79c167195a964118919e28ba679bf to your computer and use it in GitHub Desktop.
package example
type testcase struct {
name string
...
}
func TestTheTestcases(t *testing.T) {
testcases := []*testcase{...}
for _, test := range testcases {
// this is needed to keep `test` in scope. are there alternatives to this pattern?
test := test
t.Run(test.name, func(t *testing.T) {
...
})
}
}
@nullren
Copy link
Author

nullren commented May 29, 2020

oh, this is especially for when test cases are run in parallel. ie, from the docs https://godoc.org/testing

func TestGroupedParallel(t *testing.T) {
    for _, tc := range tests {
        tc := tc // capture range variable
        t.Run(tc.Name, func(t *testing.T) {
            t.Parallel()
            ...
        })
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment