如何在Golang中测试panic?

huangapple go评论93阅读模式
英文:

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

了解更多信息:

  1. Golang博客
英文:

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:

  1. Golang blog

答案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
}

huangapple
  • 本文由 发表于 2017年7月12日 16:39:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/45052597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定