核心思路是利用defer中的recover捕获panic,将程序中断事件转化为可断言的测试结果。通过在defer函数中调用recover(),能捕获预期panic并验证其值,确保测试流程可控,避免程序崩溃,从而在测试中准确验证panic行为。
在Golang中测试
panic
recover
defer
panic
panic
panic
要测试一个函数在特定条件下是否会
panic
defer
defer
recover()
recover()
nil
panic
recover()
panic
defer
panic
下面是一个具体的例子:
package main import ( "fmt" "testing" ) // SomeFunction 模拟一个在特定条件下会panic的函数 func SomeFunction(input int) { if input < 0 { panic("input cannot be negative") } if input == 0 { panic(fmt.Errorf("zero is not allowed")) } fmt.Println("Processing input:", input) } func TestSomeFunctionPanics(t *testing.T) { tests := []struct { name string input int expectedMsg string // 期望的panic消息 expectPanic bool }{ { name: "Negative input panics with string", input: -1, expectedMsg: "input cannot be negative", expectPanic: true, }, { name: "Zero input panics with error", input: 0, expectedMsg: "zero is not allowed", expectPanic: true, }, { name: "Positive input does not panic", input: 10, expectPanic: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // 设置一个defer函数来捕获panic defer func() { if r := recover(); r != nil { // 捕获到panic if !tt.expectPanic { t.Errorf("Expected no panic, but got panic: %v", r) return } // 检查panic消息是否符合预期 switch v := r.(type) { case string: if v != tt.expectedMsg { t.Errorf("Panic message mismatch. Got '%s', want '%s'", v, tt.expectedMsg) } case error: if v.Error() != tt.expectedMsg { t.Errorf("Panic error message mismatch. Got '%s', want '%s'", v.Error(), tt.expectedMsg) } default: t.Errorf("Unknown panic type: %T, value: %v", v, v) } return // 确保捕获到panic后不再执行后续的检查 } // 没有捕获到panic if tt.expectPanic { t.Errorf("Expected panic, but got none") } }() // 调用可能panic的函数 SomeFunction(tt.input) }) } }
panic
recover
我们都知道,Go语言中的
panic
recover
testing
recover
panic
立即学习“go语言免费学习笔记(深入)”;
直接调用一个会
panic
testing.T
testing.T
panic
t.Errorf
t.Fatal
这时候,
recover
defer
panic
panic
recover
panic
recover
panic
panic
panic
panic
要让
panic
defer
recover
首先,让panic
panic
panic
SomeFunction
panic
其次,让panic
panic
error
fmt.Errorf
error
panic
recover
error
panic(fmt.Errorf("invalid config: missing %s", key))
panic("bad config")
panic
再者,隔离panic
panic
panic
panic
panic
最后,利用表驱动测试。就像上面的示例代码那样,将不同的输入、预期
panic
panic
panic
panic
recover
error
这是一个我经常思考的问题:什么时候该
panic
error
error
error
error
error
error
panic
panic
panic
nil
nil
nil
panic
recover
在测试中,我们使用recover
panic
panic
recover
panic
panic
panic
error
panic
所以,选择
panic
error
panic
panic
recover
以上就是Golang测试panic行为 recover捕获验证的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号