-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
82c5772
commit 3fb96b7
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!") | ||
} | ||
}) | ||
} |