Skip to content

Instantly share code, notes, and snippets.

@prateek
Created May 6, 2018 03:32
Show Gist options
  • Save prateek/54b7c1d7bd4baaa539f95d5b41c454f8 to your computer and use it in GitHub Desktop.
Save prateek/54b7c1d7bd4baaa539f95d5b41c454f8 to your computer and use it in GitHub Desktop.
gomock.Reporter
// Package test contains utility methods for testing.
package test
import (
"fmt"
"testing"
"github.com/golang/mock/gomock"
)
// Reporter wraps a *testing.T, and provides a more useful failure mode
// when interacting with gomock.Controller.
//
// For example, consider:
// func TestMyThing(t *testing.T) {
// mockCtrl := gomock.NewController(t)
// defer mockCtrl.Finish()
// mockObj := something.NewMockMyInterface(mockCtrl)
// go func() {
// mockObj.SomeMethod(4, "blah")
// }
// }
//
// It hangs without any indication that it's missing an EXPECT() on `mockObj`.
// Providing the Reporter to the gomock.Controller ctor avoids this, and terminates
// with useful feedback. i.e.
// func TestMyThing(t *testing.T) {
// mockCtrl := gomock.NewController(test.Reporter{t})
// defer mockCtrl.Finish()
// mockObj := something.NewMockMyInterface(mockCtrl)
// go func() {
// mockObj.SomeMethod(4, "blah") // crashes the test now
// }
// }
type Reporter struct {
T *testing.T
}
// ensure Reporter implements gomock.TestReporter.
var _ gomock.TestReporter = Reporter{}
// Errorf is equivalent testing.T.Errorf.
func (r Reporter) Errorf(format string, args ...interface{}) {
r.T.Errorf(format, args...)
}
// Fatalf crashes the program with a panic to allow users to diagnose
// missing expects.
func (r Reporter) Fatalf(format string, args ...interface{}) {
panic(fmt.Sprintf(format, args...))
}
@prateek
Copy link
Author

prateek commented Jun 20, 2019

This is awesome! You saved my life!

Glad to hear it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment