package helloworldimport ("fmt""os""testing")func TestTest(t *testing.T) {fmt.Println(1)}func customFunc(m *testing.M) int {fmt.Println(2)defer func() {fmt.Println(3)}()return m.Run()}func TestMain(m *testing.M) {fmt.Println(4)os.Exit(customFunc(m))}
最终输出的顺序是:4 -> 2 -> 1 -> 3
因此,我们可以在测试时,在类似 customFunc 中,做一些前置操作,如果需要再在相应的 defer 处,做一些副作用的清理工作。
