Skip to content

Commit 2be05c2

Browse files
committed
feat: add Panic and NotPanic.
1 parent 0624608 commit 2be05c2

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

assertion.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,13 @@ func (a *Assertion) Equal(actual, expect any, message ...string) error {
2424
func (a *Assertion) NotEqual(actual, expect any, message ...string) error {
2525
return NotEqual(a.t, actual, expect, message...)
2626
}
27+
28+
// Panic expects the function fn to panic.
29+
func (a *Assertion) Panic(fn func(), message ...string) (err error) {
30+
return Panic(a.t, fn, message...)
31+
}
32+
33+
// NotPanic asserts that the function fn does not panic.
34+
func (a *Assertion) NotPanic(fn func(), message ...string) (err error) {
35+
return NotPanic(a.t, fn, message...)
36+
}

panic.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package assert
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
// Panic expects the function fn to panic.
9+
func Panic(t *testing.T, fn func(), message ...string) (err error) {
10+
defer func() {
11+
if e := recover(); e == nil {
12+
err = newAssertionError("mssing expected panic", message...)
13+
}
14+
}()
15+
16+
fn()
17+
18+
// err = newAssertionError("mssing expected panic", message...)
19+
20+
return
21+
}
22+
23+
// NotPanic asserts that the function fn does not panic.
24+
func NotPanic(t *testing.T, fn func(), message ...string) (err error) {
25+
defer func() {
26+
if e := recover(); e != nil {
27+
err = newAssertionError(fmt.Sprintf("got unwanted error: %v", e), message...)
28+
}
29+
}()
30+
31+
fn()
32+
33+
return
34+
}

panic_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package assert
2+
3+
import "testing"
4+
5+
func TestPanic(t *testing.T) {
6+
mockT := new(testing.T)
7+
a := New(mockT)
8+
9+
if err := a.Panic(func() {
10+
panic("expected panic")
11+
}); err != nil {
12+
t.Errorf("Panic() = %v, want = nil", err)
13+
}
14+
15+
if err := a.Panic(func() {
16+
// no panic
17+
}); err == nil {
18+
t.Error("Panic() = nil, want error")
19+
}
20+
}
21+
22+
func TestNotPanic(t *testing.T) {
23+
mockT := new(testing.T)
24+
a := New(mockT)
25+
26+
if err := a.NotPanic(func() {
27+
// no panic
28+
}); err != nil {
29+
t.Errorf("NotPanic() = %v, want = nil", err)
30+
}
31+
32+
if err := a.NotPanic(func() {
33+
panic("unexpected panic")
34+
}); err == nil {
35+
t.Error("NotPanic() = nil, want error")
36+
}
37+
}

0 commit comments

Comments
 (0)