简体   繁体   中英

How to test a panic in Golang?

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?

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM