Involved Source Filescall.gocallset.go
Package gomock is a mock framework for Go.
Standard usage:
(1) Define an interface that you wish to mock.
type MyInterface interface {
SomeMethod(x int64, y string)
}
(2) Use mockgen to generate a mock from the interface.
(3) Use the mock in a test:
func TestMyThing(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockObj := something.NewMockMyInterface(mockCtrl)
mockObj.EXPECT().SomeMethod(4, "blah")
// pass mockObj to a real object and play with it.
}
By default, expected calls are not enforced to run in any particular order.
Call order dependency can be enforced by use of InOrder and/or Call.After.
Call.After can create more varied call order dependencies, but InOrder is
often more convenient.
The following examples create equivalent call order dependencies.
Example of using Call.After to chain expected call order:
firstCall := mockObj.EXPECT().SomeMethod(1, "first")
secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall)
mockObj.EXPECT().SomeMethod(3, "third").After(secondCall)
Example of using InOrder to declare expected call order:
gomock.InOrder(
mockObj.EXPECT().SomeMethod(1, "first"),
mockObj.EXPECT().SomeMethod(2, "second"),
mockObj.EXPECT().SomeMethod(3, "third"),
)
matchers.go
Code Examples
{
t := &testing.T{}
ctrl := gomock.NewController(t)
mockIndex := NewMockFoo(ctrl)
var s string
mockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn(
func(arg string) interface{} {
s = arg
return "I'm sleepy"
},
)
r := mockIndex.Bar("foo")
fmt.Printf("%s %s", r, s)
}
{
t := &testing.T{}
ctrl := gomock.NewController(t)
mockIndex := NewMockFoo(ctrl)
mockIndex.EXPECT().Bar(gomock.Any()).DoAndReturn(
func(arg string) string {
time.Sleep(1 * time.Millisecond)
return "I'm sleepy"
},
)
r := mockIndex.Bar("foo")
fmt.Println(r)
}
Package-Level Type Names (total 21, in which 8 are exported)
/* sort exporteds by: | */
Call represents an expected call to a mock.
actions are called when this Call is called. Each action gets the args and
can set the return values by returning a non-nil slice. Actions run in the
order they are created.
// the args
Expectations
// the name of the method
// the type of the method
Expectations
// actual number made
// file and line number of call setup
// prerequisite calls
// the receiver of the method call
// for triggering test failures on invalid call setup
After declares that the call may only match after preReq has been exhausted.
AnyTimes allows the expectation to be called 0 or more times
Do declares the action to run when the call is matched. The function's
return values are ignored to retain backward compatibility. To use the
return values call DoAndReturn.
It takes an interface{} argument to support n-arity functions.
DoAndReturn declares the action to run when the call is matched.
The return values from this function are returned by the mocked function.
It takes an interface{} argument to support n-arity functions.
MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes was
previously called with 1, MaxTimes also sets the minimum number of calls to 0.
MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimes
was previously called with 1, MinTimes also sets the maximum number of calls to infinity.
Return declares the values to be returned by the mocked function call.
SetArg declares an action that will set the nth argument's value,
indirected through a pointer. Or, in the case of a slice, SetArg
will copy value's elements into the nth argument.
(*Call) String() string
Times declares the exact number of times a function call is expected to be executed.
(*Call) addAction(action func([]interface{}) []interface{})(*Call) call() []func([]interface{}) []interface{}
dropPrereqs tells the expected Call to not re-check prerequisite calls any
longer, and to return its current set.
Returns true if the maximum number of calls have been made.
isPreReq returns true if other is a direct or indirect prerequisite to c.
Tests if the given call matches the expected call.
If yes, returns nil. If no, returns error with message explaining why it does not match.
Returns true if the minimum number of calls have been made.
*Call : expvar.Var
*Call : fmt.Stringer
*Call : github.com/aws/smithy-go/middleware.stringer
*Call : context.stringer
*Call : runtime.stringer
func (*Call).After(preReq *Call) *Call
func (*Call).AnyTimes() *Call
func (*Call).Do(f interface{}) *Call
func (*Call).DoAndReturn(f interface{}) *Call
func (*Call).MaxTimes(n int) *Call
func (*Call).MinTimes(n int) *Call
func (*Call).Return(rets ...interface{}) *Call
func (*Call).SetArg(n int, value interface{}) *Call
func (*Call).Times(n int) *Call
func (*Controller).RecordCall(receiver interface{}, method string, args ...interface{}) *Call
func (*Controller).RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call
func go.pact.im/x/clock/mockclock.(*MockClockMockRecorder).Now() *Call
func go.pact.im/x/clock/mockclock.(*MockClockMockRecorder).Schedule(d, f interface{}) *Call
func go.pact.im/x/clock/mockclock.(*MockClockMockRecorder).Ticker(d interface{}) *Call
func go.pact.im/x/clock/mockclock.(*MockClockMockRecorder).Timer(d interface{}) *Call
func go.pact.im/x/clock/mockclock.(*MockTickerMockRecorder).C() *Call
func go.pact.im/x/clock/mockclock.(*MockTickerMockRecorder).Reset(arg0 interface{}) *Call
func go.pact.im/x/clock/mockclock.(*MockTickerMockRecorder).Stop() *Call
func go.pact.im/x/clock/mockclock.(*MockTimerMockRecorder).C() *Call
func go.pact.im/x/clock/mockclock.(*MockTimerMockRecorder).Reset(arg0 interface{}) *Call
func go.pact.im/x/clock/mockclock.(*MockTimerMockRecorder).Stop() *Call
func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call
func (*Call).dropPrereqs() (preReqs []*Call)
func go.pact.im/x/clock/mockclock.(*MockClockMockRecorder).private() *Call
func InOrder(calls ...*Call)
func (*Call).After(preReq *Call) *Call
func (*Call).isPreReq(other *Call) bool
A Controller represents the top-level control of a mock ecosystem. It
defines the scope and lifetime of mock objects, as well as their
expectations. It is safe to call Controller's methods from multiple
goroutines. Each test should create a new Controller and invoke Finish via
defer.
func TestFoo(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// ..
}
func TestBar(t *testing.T) {
t.Run("Sub-Test-1", st) {
ctrl := gomock.NewController(st)
defer ctrl.Finish()
// ..
})
t.Run("Sub-Test-2", st) {
ctrl := gomock.NewController(st)
defer ctrl.Finish()
// ..
})
})
T should only be called within a generated mock. It is not intended to
be used in user code and may be changed in future versions. T is the
TestReporter passed in when creating the Controller via NewController.
If the TestReporter does not implement a TestHelper it will be wrapped
with a nopTestHelper.
expectedCalls*callSetfinishedboolmusync.Mutex
Call is called by a mock. It should not be called by user code.
Finish checks to see if all the methods that were expected to be called
were called. It should be invoked for each Controller. It is not idempotent
and therefore can only be invoked once.
New in go1.14+, if you are passing a *testing.T into NewController function you no
longer need to call ctrl.Finish() in your test methods.
RecordCall is called by a mock. It should not be called by user code.
RecordCallWithMethodType is called by a mock. It should not be called by user code.
(*Controller) finish(cleanup bool, panicErr interface{})
func NewController(t TestReporter) *Controller
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context)
func go.pact.im/x/clock/mockclock.NewMockClock(ctrl *Controller) *mockclock.MockClock
func go.pact.im/x/clock/mockclock.NewMockTicker(ctrl *Controller) *mockclock.MockTicker
func go.pact.im/x/clock/mockclock.NewMockTimer(ctrl *Controller) *mockclock.MockTimer
GotFormatter is used to better print failure messages. If a matcher
implements GotFormatter, it will use the result from Got when printing
the failure message.
Got is invoked with the received value. The result is used when
printing the failure message.
GotFormatterFunc
func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher
GotFormatterFunc type is an adapter to allow the use of ordinary
functions as a GotFormatter. If f is a function with the appropriate
signature, GotFormatterFunc(f) is a GotFormatter that calls f.
Got implements GotFormatter.
GotFormatterFunc : GotFormatter
StringerFunc type is an adapter to allow the use of ordinary functions as
a Stringer. If f is a function with the appropriate signature,
StringerFunc(f) is a Stringer that calls f.
String implements fmt.Stringer.
StringerFunc : expvar.Var
StringerFunc : fmt.Stringer
StringerFunc : github.com/aws/smithy-go/middleware.stringer
StringerFunc : context.stringer
StringerFunc : runtime.stringer
TestHelper is a TestReporter that has the Helper method. It is satisfied
by the standard library's *testing.T.
( TestHelper) Errorf(format string, args ...interface{})( TestHelper) Fatalf(format string, args ...interface{})( TestHelper) Helper()
*testing.B
*testing.F
*testing.T
testing.TB(interface)
*cancelReporter
*nopTestHelper
*testing.common
TestHelper : TestReporter
TestHelper : go.uber.org/goleak.testHelper
TestHelper : gotest.tools/v3/assert.helperT
TestHelper : gotest.tools/v3/internal/assert.helperT
func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call
callSet represents a set of expected calls, indexed by receiver and method
name.
Calls that have been exhausted.
Calls that are still expected.
Add adds a new expected call.
Failures returns the calls that are not satisfied.
FindMatch searches for a matching call. Returns error with explanation message if no call matched.
Remove removes an expected call.
func newCallSet() *callSet
cleanuper is used to check if TestHelper also has the `Cleanup` method. A
common pattern is to pass in a `*testing.T` to
`NewController(t TestReporter)`. In Go 1.14+, `*testing.T` has a cleanup
method. This can be utilized to call `Finish()` so the caller of this library
does not have to.
( cleanuper) Cleanup(func())
*testing.B
*testing.F
*testing.T
testing.TB(interface)
*testing.common
func isCleanuper(t TestReporter) (cleanuper, bool)
Package-Level Functions (total 20, in which 13 are exported)
All returns a composite Matcher that returns true if and only all of the
matchers return true.
Any returns a matcher that always matches.
AssignableToTypeOf is a Matcher that matches if the parameter to the mock
function is assignable to the type of the parameter to this function.
Example usage:
var s fmt.Stringer = &bytes.Buffer{}
AssignableToTypeOf(s).Matches(time.Second) // returns true
AssignableToTypeOf(s).Matches(99) // returns false
var ctx = reflect.TypeOf((*context.Context)(nil)).Elem()
AssignableToTypeOf(ctx).Matches(context.Background()) // returns true
Eq returns a matcher that matches on equality.
Example usage:
Eq(5).Matches(5) // returns true
Eq(5).Matches(4) // returns false
GotFormatterAdapter attaches a GotFormatter to a Matcher.
InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order.
Example usage:
InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true
InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false
InOrder declares that the given calls should occur in order.
Len returns a matcher that matches on length. This matcher returns false if
is compared to a type that is not an array, chan, map, slice, or string.
NewController returns a new Controller. It is the preferred way to create a
Controller.
New in go1.14+, if you are passing a *testing.T into this function you no
longer need to call ctrl.Finish() in your test methods.
Nil returns a matcher that matches if the received value is nil.
Example usage:
var x *bytes.Buffer
Nil().Matches(x) // returns true
x = &bytes.Buffer{}
Nil().Matches(x) // returns false
Not reverses the results of its given child matcher.
Example usage:
Not(Eq(5)).Matches(4) // returns true
Not(Eq(5)).Matches(5) // returns false
WantFormatter modifies the given Matcher's String() method to the given
Stringer. This allows for control on how the "Want" is formatted when
printing .
WithContext returns a new Controller and a Context, which is cancelled on any
fatal failure.
callerInfo returns the file:line of the call site. skip is the number
of stack frames to skip when reporting. 0 is callerInfo's call site.