如何在Golang中测试panic?

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

How to test a panic in Golang?

问题

问题:当我传递垃圾 JSON 文件时,它似乎会发生 panic,并且不执行任何 So 语句。如何修复这个问题?

翻译结果:
好像当我传递垃圾 JSON 文件时,它会发生 panic,并且不执行任何 So 语句。如何修复这个问题?

英文:
  1. func good(json) string {
  2. \\do something
  3. err = json.Unmarshal(body, &list)
  4. if err != nil {
  5. panic(fmt.Sprintf("Unable to parse json %s",err))
  6. }
  7. }
  8. func Testgood_PanicStatement(t *testing.T) {
  9. Convey("And Invalid Json return error",t, func() {
  10. actual := good("garbage json")
  11. So(func() {},shoulPanic)
  12. So(actual ,ShouldEqual,"")
  13. }
  14. }

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()。

  1. func Testgood_PanicStatement(t *testing.T) {
  2. Convey("And Invalid Json return error",t, func() {
  3. defer func() {
  4. if r := recover(); r != nil {
  5. So(func() {},shouldPanic)
  6. So(actual ,ShouldEqual,"")
  7. }
  8. }()
  9. actual := good("garbage json")
  10. }
  11. }

了解更多信息:

  1. Golang博客
英文:

Use recover().

  1. func Testgood_PanicStatement(t *testing.T) {
  2. Convey("And Invalid Json return error",t, func() {
  3. defer func() {
  4. if r := recover(); r != nil {
  5. So(func() {},shouldPanic)
  6. So(actual ,ShouldEqual,"")
  7. }
  8. }()
  9. actual := good("garbage json")
  10. }
  11. }

Lear more about:

  1. Golang blog

答案2

得分: 3

sadlil的答案标记为正确,我想指出,恐慌函数不是一个好的实践。相反,应该将恐慌转换为函数内部的错误,并测试该错误。

  1. func good(json) (s string, err error) {
  2. defer func() {
  3. if r := recover(); r != nil {
  4. err = fmt.Errorf("good函数中出现错误:%v", r)
  5. }
  6. }()
  7. // 做一些操作
  8. err = json.Unmarshal(body, &list)
  9. if err != nil {
  10. // 为了演示,保留了panic语句。在这种情况下,你可以直接返回空字符串和err
  11. panic(fmt.Sprintf("无法解析json:%s", err))
  12. }
  13. return
  14. }
英文:

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.

  1. func good(json) (s string, err error) {
  2. defer func() {
  3. if r := recover(); r != nil {
  4. err = fmt.Errorf("Error in good: %v", r)
  5. }
  6. }()
  7. \\do something
  8. err = json.Unmarshal(body, &list)
  9. if err != nil {
  10. # leaving the panic statement for demonstration. In this case
  11. # you could just: return "", err
  12. panic(fmt.Sprintf("Unable to parse json %s",err))
  13. }
  14. return
  15. }

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:

确定