Skip to content

Commit

Permalink
Add testingx package (#127)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephen-soltesz authored Sep 9, 2020
1 parent 82c5772 commit 3fb96b7
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
37 changes: 37 additions & 0 deletions testingx/testingx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package testingx

import (
"fmt"
)

// FatalReporter defines the interface for reporting a fatal test.
type FatalReporter interface {
Fatal(args ...interface{})
Helper()
}

// Must allows the rtx.Must pattern within a unit test and will call t.Fatal if
// passed a non-nil error. The fatal message is specified as the prefix
// argument. If any further args are passed, then the prefix will be treated as
// a format string.
//
// The main purpose of this function is to turn the common pattern of:
// err := Func()
// if err != nil {
// t.Fatalf("Helpful message (error: %v)", err)
// }
// into a simplified pattern of:
// Must(t, Func(), "Helpful message")
//
// This has the benefit of using fewer lines and verifying unit tests are
// "correct by inspection".
func Must(t FatalReporter, err error, prefix string, args ...interface{}) {
t.Helper() // Excludes this function from the line reported by t.Fatal.
if err != nil {
suffix := fmt.Sprintf(" (error: %v)", err)
if len(args) != 0 {
prefix = fmt.Sprintf(prefix, args...)
}
t.Fatal(prefix + suffix)
}
}
30 changes: 30 additions & 0 deletions testingx/testingx_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package testingx

import (
"errors"
"testing"
)

type fakeReporter struct {
called int
}

func (f *fakeReporter) Helper() {}
func (f *fakeReporter) Fatal(args ...interface{}) {
f.called++
}

func TestMust(t *testing.T) {
t.Run("success", func(t *testing.T) {
f := &fakeReporter{}
Must(f, nil, "print nothing")
if f.called != 0 {
t.Fatal("t.Fatal called with nil error!")
}
err := errors.New("fake error")
Must(f, err, "print nothing: %s", "custom args")
if f.called != 1 {
t.Fatal("t.Fatal NOT called with non-nil error!")
}
})
}

0 comments on commit 3fb96b7

Please sign in to comment.