1. package helloworld
    2. import (
    3. "fmt"
    4. "os"
    5. "testing"
    6. )
    7. func TestTest(t *testing.T) {
    8. fmt.Println(1)
    9. }
    10. func customFunc(m *testing.M) int {
    11. fmt.Println(2)
    12. defer func() {
    13. fmt.Println(3)
    14. }()
    15. return m.Run()
    16. }
    17. func TestMain(m *testing.M) {
    18. fmt.Println(4)
    19. os.Exit(customFunc(m))
    20. }

    最终输出的顺序是:4 -> 2 -> 1 -> 3

    因此,我们可以在测试时,在类似 customFunc 中,做一些前置操作,如果需要再在相应的 defer 处,做一些副作用的清理工作。