LoginSignup
7
6

More than 3 years have passed since last update.

Goでpanicになる処理をテストする

Last updated at Posted at 2018-10-03

panicが発生するコードをテストする際に、どのように書けばいいのか分からなかった。
deferで指定した関数はpanic発生後も実行されるので、その関数内でrecover()する事でテスト出来る事を知ったので記録しておく。
recover()の戻り値にはpanicが発生した時に渡された文字列が返るためその値をチェックする事で判別ができる。

panic.go
package panic

func SuccessOrPanic(isSuccess bool) bool {
    // 何かしらの判定
    if isSuccess {
        return true
    }

    panic("illegal processing")
}
panic_test.go
package panic_test

import "testing"

func TestSuccessOrPanic(t *testing.T) {
    defer func() {
        err := recover()
        if err != "illegal processing" {
            t.Errorf("got %v\nwant %v", err, "illegal processing")
        }
    }()

    SuccessOrPanic(false)
}
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6