英文:
How to test a panic in Golang?
问题
问题:当我传递垃圾 JSON 文件时,它似乎会发生 panic,并且不执行任何 So 语句。如何修复这个问题?
翻译结果:
好像当我传递垃圾 JSON 文件时,它会发生 panic,并且不执行任何 So 语句。如何修复这个问题?
英文:
func good(json) string {
\\do something
err = json.Unmarshal(body, &list)
if err != nil {
panic(fmt.Sprintf("Unable to parse json %s",err))
}
}
func Testgood_PanicStatement(t *testing.T) {
Convey("And Invalid Json return error",t, func() {
actual := good("garbage json")
So(func() {},shoulPanic)
So(actual ,ShouldEqual,"")
}
}
Outcome
Line 34: - Unable to parse json ,{%!e(string=invalid character '{' looking for beginning of object key string) %!e(int64=50)}
goroutine 8 [running]:
Question:It seems like when I am passing garbage json file.It is panicking and doesn't execute any of the So statements?How to fix it?
答案1
得分: 4
使用recover()。
func Testgood_PanicStatement(t *testing.T) {
Convey("And Invalid Json return error",t, func() {
defer func() {
if r := recover(); r != nil {
So(func() {},shouldPanic)
So(actual ,ShouldEqual,"")
}
}()
actual := good("garbage json")
}
}
了解更多信息:
英文:
Use recover().
func Testgood_PanicStatement(t *testing.T) {
Convey("And Invalid Json return error",t, func() {
defer func() {
if r := recover(); r != nil {
So(func() {},shouldPanic)
So(actual ,ShouldEqual,"")
}
}()
actual := good("garbage json")
}
}
Lear more about:
答案2
得分: 3
将sadlil的答案标记为正确,我想指出,恐慌函数不是一个好的实践。相反,应该将恐慌转换为函数内部的错误,并测试该错误。
func good(json) (s string, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("good函数中出现错误:%v", r)
}
}()
// 做一些操作
err = json.Unmarshal(body, &list)
if err != nil {
// 为了演示,保留了panic语句。在这种情况下,你可以直接返回空字符串和err
panic(fmt.Sprintf("无法解析json:%s", err))
}
return
}
英文:
Upvoting the answer of sadlil as correct I want to point out, that panicking functions are not good practice. Rather convert the panic into an error INSIDE the function and test the error instead.
func good(json) (s string, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Error in good: %v", r)
}
}()
\\do something
err = json.Unmarshal(body, &list)
if err != nil {
# leaving the panic statement for demonstration. In this case
# you could just: return "", err
panic(fmt.Sprintf("Unable to parse json %s",err))
}
return
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论