Golangでpanicを含んだ関数のテストの書き方

package main

import "fmt"

func main() {
    fmt.Println(a(2))
    fmt.Println(a(0.2))
}

func a(number float64) float64 {
    if number < 1 {
        panic("must be number >= 1")
    }
    return number * number
}
package main

import (
    "fmt"
    "testing"
)

func TestA(t *testing.T) {
    tests := []struct {
        Number float64
        Panic  bool
        Want   float64
    }{
        {
            Number: 1,
            Panic:  false,
            Want:   1,
        }, {
            Number: 2,
            Panic:  false,
            Want:   4,
        }, {
            Number: -1,
            Panic:  true,
            Want:   0,
        },
    }
    for i, test := range tests {
        if test.Panic {
            f := func() { a(test.Number) }
            s := fmt.Sprint("case ", i)
            testpanics(f, s, t)
            continue
        }
        if a(test.Number) != test.Want {
            t.Errorf("mismatch case %v: expected %v,  foud %v", i, test.Number, test.Want)
        }
    }
}

func panics(f func()) (b bool) {
    defer func() {
        err := recover()
        if err != nil {
            b = true
        }
    }()
    f()
    return
}

func testpanics(f func(), name string, t *testing.T) {
    b := panics(f)
    if !b {
        t.Errorf("%s shoud panic and does not", name)
    }
}

参考

https://github.com/gonum/blas/blob/447542bc23b84f8daa64470951a57bb6713d15a1/testblas/level1double.go

https://github.com/gonum/blas/blob/447542bc23b84f8daa64470951a57bb6713d15a1/testblas/common.go

github.com