3
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?

techno
  • 111
  • 3
  • 14

2 Answers2

4

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
sadlil
  • 3,077
  • 5
  • 23
  • 36
3

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
}
TehSphinX
  • 6,536
  • 1
  • 24
  • 34