Skip to content

Commit 8585d8d

Browse files
authored
Add PanicAssertionFunc (#1337, #730)
Add a `PanicAssertionFunc` to ease writing table-driven tests for panic assertion. Closes #730
1 parent bb548d0 commit 8585d8d

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

assert/assertions.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
4545
// for table driven tests.
4646
type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
4747

48+
// PanicAssertionFunc is a common function prototype when validating a panic value. Can be useful
49+
// for table driven tests.
50+
type PanicAssertionFunc = func(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
51+
4852
// Comparison is a custom function that returns true on success and false on failure
4953
type Comparison func() (success bool)
5054

assert/assertions_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2789,6 +2789,42 @@ func TestErrorAssertionFunc(t *testing.T) {
27892789
}
27902790
}
27912791

2792+
func ExamplePanicAssertionFunc() {
2793+
t := &testing.T{} // provided by test
2794+
2795+
tests := []struct {
2796+
name string
2797+
panicFn PanicTestFunc
2798+
assertion PanicAssertionFunc
2799+
}{
2800+
{"with panic", func() { panic(nil) }, Panics},
2801+
{"without panic", func() {}, NotPanics},
2802+
}
2803+
2804+
for _, tt := range tests {
2805+
t.Run(tt.name, func(t *testing.T) {
2806+
tt.assertion(t, tt.panicFn)
2807+
})
2808+
}
2809+
}
2810+
2811+
func TestPanicAssertionFunc(t *testing.T) {
2812+
tests := []struct {
2813+
name string
2814+
panicFn PanicTestFunc
2815+
assertion PanicAssertionFunc
2816+
}{
2817+
{"not panic", func() {}, NotPanics},
2818+
{"panic", func() { panic(nil) }, Panics},
2819+
}
2820+
2821+
for _, tt := range tests {
2822+
t.Run(tt.name, func(t *testing.T) {
2823+
tt.assertion(t, tt.panicFn)
2824+
})
2825+
}
2826+
}
2827+
27922828
func TestEventuallyFalse(t *testing.T) {
27932829
mockT := new(testing.T)
27942830

0 commit comments

Comments
 (0)