testing.M在golang中恢复

This recovery works:

func TestSomeTest(t *testing.T) {
    defer func() {
        r := recover()
        fmt.Println("recovery")
        fmt.Println(r)
    }()
    panic("panic here")
}

But this does not:

func TestSomeTest(t *testing.T) {
    panic("panic here")
}

func TestMain(m *testing.M) {
    defer func() {
        r := recover()
        fmt.Println("recovery")
        fmt.Println(r)
    }()
    ret := m.Run()
    os.Exit(ret)
}

Why? I expect that panic here will be recovered by code in func TestMain(m *testing.M). Why not? I just have panic without any recovery in this case.

Full code:

package main

import (
    "fmt"
    "os"
    "testing"
)

func TestSomeTest(t *testing.T) {
    // defer func() {
    //  r := recover()
    //  fmt.Println("recovery")
    //  fmt.Println(r)
    // }()
    panic("panic here")
}

func TestMain(m *testing.M) {
    defer func() {
        r := recover()
        fmt.Println("recovery")
        fmt.Println(r)
    }()
    ret := m.Run()
    os.Exit(ret)
}

To run this code I used go test command.

查看全部
duancaozen6066
duancaozen6066
2015/04/15 14:08
  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复