go - testing.M 在 golang 中恢复

标签 go

此恢复有效:

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

但这不是:

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)
}

为什么? 我希望 panic here 将通过 func TestMain(m *testing.M) 中的代码恢复。为什么不?在这种情况下,我只有 panic 而没有任何 recovery

完整代码:

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)
}

为了运行这段代码,我使用了 go test 命令。

最佳答案

这是因为测试是在单独的 goroutine 中运行的。

这就像您的第一个示例发送了一个无法恢复的 goroutine。

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

    go func() {
        // won't recover
        panic("panic here")
    }()
    time.Sleep(time.Second)
}

关于go - testing.M 在 golang 中恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29652530/

相关文章:

go - 如何使用反射设置作为指向任意值的指针的结构成员

amazon-web-services - 使用AWS开发工具包Go从Fargate任务中的角色加载AWS凭证的正确方法是什么?

go - 为什么Goroutines与顺序执行所花的时间几乎相同?

go - 不能发布多个文件

arrays - 在 Golang 中检查 IP 地址 slice 中的 IP 的有效方法

mongodb - 在 n 天后删除 MongoDB 文档

string - 如何用随机替换词有效地替换字符串中的词?

Golang bytes.Buffer - 传递值问题

go - 从go中的另一个文件导入 map 变量

mongodb - mgo,mongodb : find one document that is embedded and part of an array