jsonunit-testinggogoconvey

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?


Solution

  • 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