{ // }{ "Case 1": {}, } for name, tt := range cases { t.Run(name, func(t *testing.T) { t.Parallel() // }) } } 2. You Will Leave Comments as Follows See Test parallelization in Go: Understanding the t.Parallel() method for detailed explanation.
The “T” struct can have a parent of the same type and multiple children. package testing type T struct { common isEnvSet bool context *testContext } type common struct { // parent *common sub []*T // Queue of subtests to be run in parallel. // } var t *testing.T var t *testing.T var t *testing.T t.parent t.sub
“t.Run” creates a new child “T”-typed value using its receiver as the parent. func (t *T) Run(name string, f func(t *T)) bool { // t = &T{ common: common{ // parent: &t.common, level: t.level + 1, }, context: t.context, } // go tRunner(t, f) // } var t *testing.T var t *testing.T t.parent func tRunner(t *T, fn func(t *T)) { // fn(t) // }
parent that its receiver is a child. func (t *T) Parallel() { // Add to the list of tests to be released by the parent. t.parent.sub = append(t.parent.sub, t) // } var t *testing.T var t *testing.T t.sub
adds the received function to the “cleanups” field. type common struct { // optional functions to be called at the end of the test cleanups []func() // } func (c *common) Cleanup(f func()) { // fn := func() { // f() } // c.cleanups = append(c.cleanups, fn) }
struct supports a hierarchical testing structure with a single parent of the same type and multiple child tests that are executed in parallel. 2. Building Hierarchical Testing with “t.Run” and “t.Parallel”: a. “t.Run” creates a child “T”-typed value from its receiver and executes a function, which is received as a second argument, with this child “T”-typed value. b. “t.Parallel” registers its receiver as a child to the receiver's parent. 3. Execution Order and Cleanup Process: a. Just before “t.Run” finishes, it sends a signal to its receiver to notify the end of the test. The parent “T”-typed value waits for all subtests to receive this end signal, then executes all post-processing tasks registered by “t.Cleanup”.