Movatterモバイル変換


[0]ホーム

URL:


gomock

package
v0.6.0Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2025 License:Apache-2.0Imports:10Imported by:6,514

Details

Repository

github.com/uber/mock

Links

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

The standard TestReporter most users will pass to `NewController` is a`*testing.T` from the context of the test. Note that this will use thestandard `t.Error` and `t.Fatal` methods to report what happened in the test.In some cases this can leave your testing package in a weird state if globalstate is used since `t.Fatal` is like calling panic in the middle of afunction. In these cases it is recommended that you pass in your own`TestReporter`.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

funcInOrder

func InOrder(args ...any)

InOrder declares that the given calls should occur in order.It panics if the type of any of the arguments isn't *Call or a generatedmock with an embedded *Call.

funcWithOverridableExpectationsadded inv0.2.0

func WithOverridableExpectations() overridableExpectationsOption

WithOverridableExpectations allows for overridable call expectationsi.e., subsequent call expectations override existing call expectations

Types

typeCall

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(fany) *Call

Do declares the action to run when the call is matched. The function'sreturn values are ignored to retain backward compatibility. To use thereturn values call DoAndReturn.It takes an any argument to support n-arity functions.The anonymous function must match the function signature mocked method.

func (*Call)DoAndReturn

func (c *Call) DoAndReturn(fany) *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 any argument to support n-arity functions.The anonymous function must match the function signature mocked method.

Example (CaptureArguments)
t := &testing.T{} // provided by testctrl := gomock.NewController(t)mockIndex := NewMockFoo(ctrl)var s stringmockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn(func(arg string) any {s = argreturn "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 testctrl := 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)
Output:I'm sleepy
Example (WithOverridableExpectations)
t := &testing.T{} // provided by testctrl := gomock.NewController(t, gomock.WithOverridableExpectations())mockIndex := NewMockFoo(ctrl)var s stringmockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn(func(arg string) any {s = argreturn "I'm sleepy"},)r := mockIndex.Bar("foo")fmt.Printf("%s %s", r, s)
Output:I'm sleepy foo

func (*Call)MaxTimes

func (c *Call) MaxTimes(nint) *Call

MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes waspreviously called with 1, MaxTimes also sets the minimum number of calls to 0.

func (*Call)MinTimes

func (c *Call) MinTimes(nint) *Call

MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimeswas previously called with 1, MinTimes also sets the maximum number of calls to infinity.

func (*Call)Return

func (c *Call) Return(rets ...any) *Call

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

func (*Call)SetArg

func (c *Call) SetArg(nint, valueany) *Call

SetArg declares an action that will set the nth argument's value,indirected through a pointer. Or, in the case of a slice and map, SetArgwill copy value's elements/key-value pairs into the nth argument.

func (*Call)String

func (c *Call) String()string

func (*Call)Times

func (c *Call) Times(nint) *Call

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

typeController

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.TTestHelper// contains filtered or unexported fields}

A Controller represents the top-level control of a mock ecosystem. Itdefines the scope and lifetime of mock objects, as well as theirexpectations. It is safe to call Controller's methods from multiplegoroutines. Each test should create a new Controller.

func TestFoo(t *testing.T) {  ctrl := gomock.NewController(t)  // ..}func TestBar(t *testing.T) {  t.Run("Sub-Test-1", st) {    ctrl := gomock.NewController(st)    // ..  })  t.Run("Sub-Test-2", st) {    ctrl := gomock.NewController(st)    // ..  })})

funcNewController

func NewController(tTestReporter, opts ...ControllerOption) *Controller

NewController returns a new Controller. It is the preferred way to create a Controller.

Passing*testing.T registers cleanup function to automatically callController.Finishwhen the test and all its subtests complete.

funcWithContext

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

func (*Controller)Call

func (ctrl *Controller) Call(receiverany, methodstring, args ...any) []any

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 is not idempotent and therefore can only be invoked once.

Note: If you pass a *testing.T intoNewController, you no longerneed to call ctrl.Finish() in your test methods.

func (*Controller)RecordCall

func (ctrl *Controller) RecordCall(receiverany, methodstring, args ...any) *Call

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

func (*Controller)RecordCallWithMethodType

func (ctrl *Controller) RecordCallWithMethodType(receiverany, methodstring, methodTypereflect.Type, args ...any) *Call

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

func (*Controller)Satisfiedadded inv0.2.0

func (ctrl *Controller) Satisfied()bool

Satisfied returns whether all expected calls bound to this Controller have been satisfied.Calling Finish is then guaranteed to not fail due to missing calls.

typeControllerOptionadded inv0.2.0

type ControllerOption interface {// contains filtered or unexported methods}

ControllerOption configures how a Controller should behave.

typeGotFormatter

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

GotFormatter is used to better print failure messages. If a matcherimplements GotFormatter, it will use the result from Got when printingthe failure message.

typeGotFormatterFunc

type GotFormatterFunc func(gotany)string

GotFormatterFunc type is an adapter to allow the use of ordinaryfunctions as a GotFormatter. If f is a function with the appropriatesignature, GotFormatterFunc(f) is a GotFormatter that calls f.

func (GotFormatterFunc)Got

func (fGotFormatterFunc) Got(gotany)string

Got implements GotFormatter.

typeMatcher

type Matcher interface {// Matches returns whether x is a match.Matches(xany)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.

funcAll

func All(ms ...Matcher)Matcher

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

funcAny

func Any()Matcher

Any returns a matcher that always matches.

funcAnyOfadded inv0.4.0

func AnyOf(xs ...any)Matcher

AnyOf returns a composite Matcher that returns true if at least one of thematchers returns true.

Example usage:

AnyOf(1, 2, 3).Matches(2) // returns trueAnyOf(1, 2, 3).Matches(10) // returns falseAnyOf(Nil(), Len(2)).Matches(nil) // returns trueAnyOf(Nil(), Len(2)).Matches("hi") // returns trueAnyOf(Nil(), Len(2)).Matches("hello") // returns false

funcAssignableToTypeOf

func AssignableToTypeOf(xany)Matcher

AssignableToTypeOf is a Matcher that matches if the parameter to the mockfunction 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 trueAssignableToTypeOf(s).Matches(99) // returns falsevar ctx = reflect.TypeOf((*context.Context)(nil)).Elem()AssignableToTypeOf(ctx).Matches(context.Background()) // returns true

funcCondadded inv0.3.0

func Cond[Tany](fn func(x T)bool)Matcher

Cond returns a matcher that matches when the given function returns trueafter passing it the parameter to the mock function.This is particularly useful in case you want to match over a field of a custom struct, or dynamic logic.

Example usage:

Cond(func(x int){return x == 1}).Matches(1) // returns trueCond(func(x int){return x == 2}).Matches(1) // returns false

funcEq

func Eq(xany)Matcher

Eq returns a matcher that matches on equality.

Example usage:

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

funcGotFormatterAdapter

func GotFormatterAdapter(sGotFormatter, mMatcher)Matcher

GotFormatterAdapter attaches a GotFormatter to a Matcher.

funcInAnyOrder

func InAnyOrder(xany)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 trueInAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false

funcLen

func Len(iint)Matcher

Len returns a matcher that matches on length. This matcher returns false ifis compared to a type that is not an array, chan, map, slice, or string.

funcNil

func Nil()Matcher

Nil returns a matcher that matches if the received value is nil.

Example usage:

var x *bytes.BufferNil().Matches(x) // returns truex = &bytes.Buffer{}Nil().Matches(x) // returns false

funcNot

func Not(xany)Matcher

Not reverses the results of its given child matcher.

Example usage:

Not(Eq(5)).Matches(4) // returns trueNot(Eq(5)).Matches(5) // returns false

funcRegexadded inv0.4.0

func Regex(regexStrstring)Matcher

Regex checks whether parameter matches the associated regex.

Example usage:

Regex("[0-9]{2}:[0-9]{2}").Matches("23:02") // returns trueRegex("[0-9]{2}:[0-9]{2}").Matches([]byte{'2', '3', ':', '0', '2'}) // returns trueRegex("[0-9]{2}:[0-9]{2}").Matches("hello world") // returns falseRegex("[0-9]{2}").Matches(21) // returns false as it's not a valid type

funcWantFormatter

func WantFormatter(sfmt.Stringer, mMatcher)Matcher

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

typeStringerFunc

type StringerFunc func()string

StringerFunc type is an adapter to allow the use of ordinary functions asa Stringer. If f is a function with the appropriate signature,StringerFunc(f) is a Stringer that calls f.

func (StringerFunc)String

func (fStringerFunc) String()string

String implements fmt.Stringer.

typeTestHelper

type TestHelper interface {TestReporterHelper()}

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

typeTestReporter

type TestReporter interface {Errorf(formatstring, args ...any)Fatalf(formatstring, args ...any)}

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

Source Files

View all Source files

Directories

PathSynopsis
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 orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp