Created
May 7, 2022 23:07
-
-
Save enobufs/2d542211fb098e063d0c4fec1d855124 to your computer and use it in GitHub Desktop.
beforeEach and afterEach with go-test
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
package main | |
import ( | |
"fmt" | |
"os" | |
"runtime" | |
"testing" | |
) | |
func TestMain(m *testing.M) { | |
fmt.Println("Before All") | |
m.Run() | |
fmt.Println("After All") | |
os.Exit(0) | |
} | |
// SetBeforeAndAfterEach takes before and after functions and returns a function called by t.Run(). | |
func SetBeforeAndAfterEach(beforeFunc, afterFunc func(*testing.T)) func(func(*testing.T)) func(*testing.T) { | |
return func(test func(*testing.T)) func(*testing.T) { | |
return func(t *testing.T) { | |
if beforeFunc != nil { | |
beforeFunc(t) | |
} | |
test(t) | |
if afterFunc != nil { | |
afterFunc(t) | |
} | |
} | |
} | |
} | |
// TestSetBeforeAndAfterEach show the usage example of SetBeforeAndAfterEach | |
func TestSetBeforeAndAfterEach(t *testing.T) { | |
t.Logf("Test entered") | |
defer t.Logf("Test exited") | |
var nGoRoutine int | |
run := SetBeforeAndAfterEach( | |
func(t *testing.T) { | |
t.Logf("Before %s", t.Name()) | |
nGoRoutine = runtime.NumGoroutine() | |
}, | |
func(t *testing.T) { | |
t.Logf("After %s (goroutines: %d => %d)", t.Name(), nGoRoutine, runtime.NumGoroutine()) | |
}, | |
) | |
t.Run("subtest 1", run(func(t *testing.T) { | |
defer t.Logf("Running %s", t.Name()) | |
})) | |
t.Run("subtest 2", run(func(t *testing.T) { | |
defer t.Logf("Running %s", t.Name()) | |
})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.