Last active
January 11, 2024 01:44
-
-
Save RSheremeta/590bfd4dd8ce12d95447f39753c1ae96 to your computer and use it in GitHub Desktop.
Pure Go implementation of BeforeEach / AfterEach and BeforeSuite / AfterSuite testing mechanisms
This file contains 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
// DISCLAIMER: | |
// ideally, this snippet shouldn't be used as a separate file | |
// all the stuff should be divided into kinda logical parts and stored in files respectively | |
// it's all gathered here in one single place for the demonstration purposes only | |
package go_medium | |
import ( | |
"fmt" | |
"os" | |
"testing" | |
) | |
// a variable storing wrapped functions for the usage inside each test case | |
var Run = forEach(beforeTest, afterTest) | |
// 1. invoking our function with the steps BEFORE Suite execution | |
// 2. m.Run() - it's Suite execution actually, | |
// and we store the result of system exit code in a variable | |
// 3. invoking our function with the steps AFTER Suite execution | |
// 4. passing stored result of the system exit code into Exit() function of os pkg | |
func TestMain(m *testing.M) { | |
beforeSuite() | |
code := m.Run() | |
afterSuite() | |
os.Exit(code) | |
} | |
// these have pretty basic content inside, simply printing steps, | |
// but that's exactly what's needed for the demo purposes right now | |
func beforeSuite() { | |
fmt.Println("\n This function is invoked BEFORE the entire testing suite!") | |
} | |
func afterSuite() { | |
fmt.Println("\n This function is invoked AFTER the entire testing suite!") | |
} | |
func beforeTest() { | |
fmt.Println("\n This is a pre-condition executed BEFORE each Test!") | |
} | |
func afterTest() { | |
fmt.Println("\n This is a post-condition executed AFTER each Test!") | |
} | |
// actual before & after each mechanism key implementation | |
func forEach(before, after func()) func(func()) { | |
return func(test func()) { | |
before() | |
test() | |
after() | |
} | |
} | |
// actual tests | |
func TestA(t *testing.T) { | |
Run(func() { | |
fmt.Println("\n This is a TestA() test case") | |
}) | |
} | |
func TestB(t *testing.T) { | |
Run(func() { | |
fmt.Println("\n This is a TestB() test case") | |
}) | |
} | |
func TestC(t *testing.T) { | |
Run(func() { | |
fmt.Println("\n This is a TestC() test case") | |
t.Fail() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment