How to test panics?

前端 未结 7 526
别跟我提以往
别跟我提以往 2020-12-12 20:19

I\'m currently pondering how to write tests that check if a given piece of code panicked? I know that Go uses recover to catch panics, but unlike say, Java code, you can\'t

7条回答
  •  醉话见心
    2020-12-12 20:55

    If you use testify/assert, then it's a one-liner:

    func TestOtherFunctionThatPanics(t *testing.T) {
      assert.Panics(t, OtherFunctionThatPanics, "The code did not panic")
    }
    

    Or, if your OtherFunctionThatPanics has a signature other than func():

    func TestOtherFunctionThatPanics(t *testing.T) {
      assert.Panics(t, func() { OtherFunctionThatPanics(arg) }, "The code did not panic")
    }
    

    If you haven't tried testify yet, then also check out testify/mock. Super simple assertions and mocks.

提交回复
热议问题