Skip to content

Instantly share code, notes, and snippets.

@Nitecon
Created February 20, 2019 21:20
Show Gist options
  • Save Nitecon/3e10e05af19b13f21e77a8160f138c58 to your computer and use it in GitHub Desktop.
Save Nitecon/3e10e05af19b13f21e77a8160f138c58 to your computer and use it in GitHub Desktop.
Table driven golang panic test
package main
func addLevelPool(level int) {
if level > 9{
panic("runtime error: index out of range")
}
}
package main
import (
"reflect"
"testing"
"github.com/aws/aws-sdk-go/service/s3"
)
# Note that the function being tested here (addLevelPool) takes a single arg (level)
# if the level is greater than 9 it panics else it just sets a level.
# To test the panic I set value to 65535 which will cause funciton to panic
# This test below illustrates ability to test panics and success in a table driven format
func Test_addLevelPool(t *testing.T) {
type args struct {
level int
}
tests := []struct {
name string
args args
wantPanic string
}{
{
name: "Must Panic OOR",
args: args{level: 65536},
wantPanic: "runtime error: index out of range",
},
{
name: "Success",
args: args{level: 5},
wantPanic: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.wantPanic != "" {
defer func() {
err := recover().(error)
if err.Error() != tt.wantPanic {
t.Fatalf("Wrong panic message: %s", err.Error())
}
}()
}
addLevelPool(tt.args.level)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment