gomock

package
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 11, 2021 License: Apache-2.0 Imports: 9 Imported by: 19,947

Documentation

Overview

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"),
)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func InOrder

func InOrder(calls ...*Call)

InOrder declares that the given calls should occur in order.

Types

type Call

type Call struct {
	// contains filtered or unexported fields
}

Call represents an expected call to a mock.

func (*Call) After

func (c *Call) After(preReq *Call) *Call

After declares that the call may only match after preReq has been exhausted.

func (*Call) AnyTimes

func (c *Call) AnyTimes() *Call

AnyTimes allows the expectation to be called 0 or more times

func (*Call) Do

func (c *Call) Do(f interface{}) *Call

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.

func (*Call) DoAndReturn added in v1.0.1

func (c *Call) DoAndReturn(f interface{}) *Call

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.

Example (CaptureArguments)
t := &testing.T{} // provided by test
ctrl := gomock.NewController(t)
mockIndex := NewMockFoo(ctrl)
var s string

mockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn(
	// signature of anonymous function must have the same number of input and output arguments as the mocked method.
	func(arg string) interface{} {
		s = arg
		return "I'm sleepy"
	},
)

r := mockIndex.Bar("foo")
fmt.Printf("%s %s", r, s)
Output:

I'm sleepy foo
Example (Latency)
t := &testing.T{} // provided by test
ctrl := gomock.NewController(t)
mockIndex := NewMockFoo(ctrl)

mockIndex.EXPECT().Bar(gomock.Any()).DoAndReturn(
	// signature of anonymous function must have the same number of input and output arguments as the mocked method.
	func(arg string) string {
		time.Sleep(1 * time.Millisecond)
		return "I'm sleepy"
	},
)

r := mockIndex.Bar("foo")
fmt.Println(r)
Output:

I'm sleepy

func (*Call) MaxTimes

func (c *Call) MaxTimes(n int) *Call

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.

func (*Call) MinTimes

func (c *Call) MinTimes(n int) *Call

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.

func (*Call) Return

func (c *Call) Return(rets ...interface{}) *Call

Return declares the values to be returned by the mocked function call.

func (*Call) SetArg

func (c *Call) SetArg(n int, value interface{}) *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.

func (*Call) String

func (c *Call) String() string

func (*Call) Times

func (c *Call) Times(n int) *Call

Times declares the exact number of times a function call is expected to be executed.

type Controller

type Controller struct {
	// 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.
	T TestHelper
	// contains filtered or unexported fields
}

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()
    // ..
  })
})

func NewController

func NewController(t TestReporter) *Controller

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.

func WithContext added in v1.0.1

func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context)

WithContext returns a new Controller and a Context, which is cancelled on any fatal failure.

func (*Controller) Call

func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{}

Call is called by a mock. It should not be called by user code.

func (*Controller) Finish

func (ctrl *Controller) Finish()

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.

func (*Controller) RecordCall

func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call

RecordCall is called by a mock. It should not be called by user code.

func (*Controller) RecordCallWithMethodType

func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call

RecordCallWithMethodType is called by a mock. It should not be called by user code.

type GotFormatter added in v1.4.0

type GotFormatter interface {
	// Got is invoked with the received value. The result is used when
	// printing the failure message.
	Got(got interface{}) string
}

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.

type GotFormatterFunc added in v1.4.0

type GotFormatterFunc func(got interface{}) string

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.

func (GotFormatterFunc) Got added in v1.4.0

func (f GotFormatterFunc) Got(got interface{}) string

Got implements GotFormatter.

type Matcher

type Matcher interface {
	// Matches returns whether x is a match.
	Matches(x interface{}) bool

	// String describes what the matcher matches.
	String() string
}

A Matcher is a representation of a class of values. It is used to represent the valid or expected arguments to a mocked method.

func All added in v1.4.0

func All(ms ...Matcher) Matcher

All returns a composite Matcher that returns true if and only all of the matchers return true.

func Any

func Any() Matcher

Any returns a matcher that always matches.

func AssignableToTypeOf added in v1.2.0

func AssignableToTypeOf(x interface{}) Matcher

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

func Eq

func Eq(x interface{}) Matcher

Eq returns a matcher that matches on equality.

Example usage:

Eq(5).Matches(5) // returns true
Eq(5).Matches(4) // returns false

func GotFormatterAdapter added in v1.4.0

func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher

GotFormatterAdapter attaches a GotFormatter to a Matcher.

func InAnyOrder added in v1.6.0

func InAnyOrder(x interface{}) 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

func Len added in v1.4.0

func Len(i int) Matcher

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.

func Nil

func Nil() Matcher

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

func Not

func Not(x interface{}) Matcher

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

func WantFormatter added in v1.4.0

func WantFormatter(s fmt.Stringer, m Matcher) Matcher

WantFormatter modifies the given Matcher's String() method to the given Stringer. This allows for control on how the "Want" is formatted when printing .

type StringerFunc added in v1.4.0

type StringerFunc func() string

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.

func (StringerFunc) String added in v1.4.0

func (f StringerFunc) String() string

String implements fmt.Stringer.

type TestHelper added in v1.2.0

type TestHelper interface {
	TestReporter
	Helper()
}

TestHelper is a TestReporter that has the Helper method. It is satisfied by the standard library's *testing.T.

type TestReporter

type TestReporter interface {
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
}

A TestReporter is something that can be used to report test failures. It is satisfied by the standard library's *testing.T.

Directories

Path Synopsis
internal
mock_gomock
Package mock_gomock is a generated GoMock package.
Package mock_gomock is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL