mock

package
v0.0.51 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2026 License: MIT Imports: 9 Imported by: 0

README

Package testing/mock

Goal of this package is to provide a small extension library that provides a common mock controller interface for gomock and gock that enables a unified, highly reusable integration pattern.

Unfortunately, we had to sacrifice a bit of type-safety to allow for chaining mock calls arbitrarily during setup. Anyhow, the offered in runtime validation is a sufficient strategy to cover for the missing type-safety.

Example usage

The mock-framework provides a simple gomock handler extension to creates singleton mock controllers on demand by accepting mock constructors in its method calls. In addition, it provides a mock setup abstraction to simply setup complex mock request/response chains.

func TestUnit(t *testing.T) {
    // Given
    mocks := mock.NewMocks(t)

    setup := mock.Get(mocks, NewServiceMock).EXPECT()...

    mocks.Expect(setup)

    service := NewUnitService(
        mock.Get(mocks, NewServiceMock))

    // When
    ...
}

Using the features of the mock-framework we can design more advanced usage patterns as described in the following.

Generic mock controller setup

Usually, a new system under test must be created for each test run. Therefore, the following generic pattern to set up the mock controller with an arbitrary system under test is very useful.

func SetupUnit(
    t test.Test,
    setup mock.SetupFunc,
) (*Unit, *Mocks) {
    mocks := mock.NewMocks(t).Expect(setup)

    unit := NewUnitService(
        mock.Get(mocks, NewServiceMock)
    ).(*Unit)

    return unit, mocks
}

Note: The mock.Get(mocks, NewServiceMock) is the standard pattern to request a new or existing mock instance from the mock controller. As input, any test interface or entity compatible with the gomock.TestReporter can be used.

Generic mock call setup

Now we need to define the mock service inline or better via a function calls following the below common coding and naming pattern, that we may support by code generation in the future.

func Call(input..., output..., error) mock.SetupFunc {
    return func(mocks *mock.Mocks) any {
        return mock.Get(mocks, NewServiceMock).EXPECT().Call(input...).
            { DoAndReturn(mocks.Do(Service.Call, output..., error))
            | Return(output..., error).Do(mocks.Do(Service.Call)) }
        ]
    }
}

The pattern combines regular as well as error behavior and is out-of-the-box prepared to handle tests with detached goroutines, i.e. functions that are spawned by the system-under-test without waiting for their result.

The mock handler therefore provides a WaitGroup and automatically registers a single mock call on each request using mocks.Do(...) to notify the call completion via Do|DoAndReturn(). For test with detached goroutines the test can wait via mocks.Wait(), before finishing and checking whether the mock calls are completely consumed.

Since some arguments needed to set up a mock call may only be available after creating the test runner, the mock controller provides a dynamic key-value storage that is accessible via SetArg(key,value), SetArgs(map[key]value), and GetArg(key).

Note: Since waiting for mock calls can take literally for ever in case of test failures, it is advised to use an isolated test environment that unlocks the waiting test in case of failures and fatal errors, e.g. by using:

test.Run(test.Success, func(t *TestingT) {
    // Given
    ...

    // When
    ...
    mocks.Wait()

    // Then
})

A static series of mock service calls can now simply expressed by chaining the mock service calls as follows using mock.Chain and while defining a new mock call setup function:

func CallChain(input..., output..., error) mock.SetupFunc {
    return func(mocks *Mocks) any {
        return mock.Chain(
            CallA(input...),
            CallB(input...),
            ...
    }
}

Note: As a special test case it is possible to panic as mock a result by using Do(mocks.GetPanic(<#input-args>,<reason>)).

Generic mock ordering patterns

With the above preparations for mocking service calls we can now define the mock setup easily using the following ordering methods:

  • Chain allows to create an ordered chain of mock calls that can be combined with other setup methods that determine the predecessors and successor mock calls.

  • Parallel allows to create an unordered set of mock calls that can be combined with other setup methods that determine the predecessor and successor mock calls.

  • Setup allows to create an unordered detached set of mock calls that creates no relation to predecessors and successors it was defined with.

Beside this simple (un-)ordering methods there are two further methods for completeness, that allows control of how predecessors and successors are used to set up ordering conditions:

  • Sub allows to define a sub-set or sub-chain of elements in Parallel and Chain as predecessor and successor context for further combination.

  • Detach allows to detach an element from the predecessor context (Head), from the successor context (Tail), or from both which is used in Setup.

The application of these two functions may be a bit more complex but still follows the intuition.

Generic parameterized test pattern

The ordering methods and the mock service call setups can now be used to define the mock call expectations, in a parameter setup as follows to show the most common use cases:

var unitCallTestCases = map[string]struct {
    setup    mock.SetupFunc
    input*...    *model.*
    expect       test.Expect
    expect*...   *model.*
    expectError  error
}{
    "single mock setup": {
        setup: Call(...),
    }
    "chain mock setup": {
        setup: mock.Chain(
            CallA(...),
            CallB(...),
            ...
        )
    }
    "nested chain mock setup": {
        setup: mock.Chain(
            CallA(...),
            mock.Chain(
                CallA(...),
                CallB(...),
                ...
            ),
            CallB(...),
            ...
        )
    }
    "parallel chain mock setup": {
        setup: mock.Parallel(
            CallA(...),
            mock.Chain(
                CallB(...),
                CallC(...),
                ...
            ),
            mock.Chain(
                CallD(...),
                CallE(...),
                ...
            ),
            ...
        )
    }
    ...
}

This test parameter setup can now be use for all parameterized unit test using the following common parallel pattern, that includes mocks.Wait() to handle detached goroutines as well as the isolated test environment to unlocks the waiting group in case of failures:

func TestUnitCall(t *testing.T) {
    t.Parallel()

    for name, param := range unitCallTestCases {
        t.Run(name, test.Run(param.expect, func(t test.Test) {
            t.Parallel()

            // Given
            unit, mocks := SetupTestUnit(t, param.setup)

            // When
            result, err := unit.UnitCall(param.input*, ...)

            mocks.Wait()

            // Then
            assert.Equal(t, param.expect*, result)
            assert.Equal(t, param.expectError, err)
        }))
    }
}

Note: See Parallel tests requirements for more information on requirements in parallel parameterized tests.

Custom matchers

The mock package provides currently one custom matcher greatly improving the output compared to make finding of call differences very simple. The matcher can be provided on input value as follows:

func Call(input..., output..., error) mock.SetupFunc {
    return func(mocks *mock.Mocks) any {
        return mock.Get(mocks, NewServiceMock).EXPECT().Call(
                mocks.Equal(input1), ..., mocks.Equal(inputN)
            ).{ DoAndReturn(mocks.Do(Service.Call, output..., error))
            | Return(output..., error).Do(mocks.Do(Service.Call)) }
        ]
    }
}

The output contains improved type information as well as a regular diff of the actual and the expected value. The output can be configured by applying configuring the mock controller via the following list of functions:

    mock.Context(int)
    mock.FromFile(string)
    mock.FromDate(string)
    mock.ToFile(string)
    mock.ToDate(string)
    mock.Indent(string)
    mock.MaxDepth(int)
    mock.DisableMethods(bool)
    mock.DisablePointerMethods(bool)
    mock.DisablePointerAddresses(bool)
    mock.DisableCapabilities(bool)
    mock.ContinueOnMethods(bool)
    mock.SortKeys(bool)
    mock.SpewKeys(bool)

This allows to adjust the output as needed.

Documentation

Overview

Package mock contains the basic collection of functions and types for controlling mocks and mock request/response setup. It is part of the public interface and starting to get stable, however, we are still experimenting to optimize the interface and the user experience.

Index

Constants

View Source
const (
	// DefaultContext provides the default number of context lines to show
	// before and after the changes in a diff.
	DefaultContext = 3
	// DefaultSkippingSize is the maximum size of the string representation of
	// a value presented in the output.
	DefaultSkippingSize = 50 // bufio.MaxScanTokenSize - 100
	// DefaultSkippingTail is the size of the tail after the skipped value
	// part.
	DefaultSkippingTail = 5
)

Variables

View Source
var (
	// ErrTypeNotSupported type for unsupported type errors.
	ErrTypeNotSupported = errors.New("type not supported")

	// ErrModeNotSupported type for unsupported mode errors.
	ErrModeNotSupported = errors.New("mode not supported")
)

Functions

func Chain

func Chain(fncalls ...func(*Mocks) any) func(*Mocks) any

Chain creates a single chain of mock calls that is validated by `gomock`. If the execution order deviates from the order defined in the chain, the test validation fails. The method returns the full mock calls tree to allow chaining with other ordered setup method.

func Detach

func Detach(mode DetachMode, fncall func(*Mocks) any) func(*Mocks) any

Detach detach given mock call setup using given detach mode. It is possible to detach the mock call from the preceding mock calls (`Head`), from the succeeding mock calls (`Tail`), or from both as used in `Setup`.

func Get

func Get[T any](mocks *Mocks, creator func(*Controller) *T) *T

Get resolves the actual mock from the mock handler by providing the constructor function generated by `gomock` to create a new mock.

func GetSubSlice

func GetSubSlice[T any](from, to int, calls []T) any

GetSubSlice returns the sub slice of mock calls starting at index `from` up to index `to` including. A negative value is used to calculate an index from the end of the slice. If the index `from` is after the index `to`, the indexes are automatically switched.

func NewErrDetachMode

func NewErrDetachMode(mode DetachMode) error

NewErrDetachMode creates an error that the given detach mode is not supported.

func NewErrDetachNotAllowed

func NewErrDetachNotAllowed(mode DetachMode) error

NewErrDetachNotAllowed creates an error that the detach mode is not supported.

func NewErrNoCall

func NewErrNoCall(call any) error

NewErrNoCall creates an error with given call type to panic on incorrect call type.

func Parallel

func Parallel(fncalls ...func(*Mocks) any) func(*Mocks) any

Parallel creates a set of parallel set of mock calls that is validated by `gomock`. While the parallel setup provides some freedom, this still defines constraints with respect to parent and child setup methods, e.g. when setting up parallel chains in a chain, each parallel chains needs to follow the last mock call and finish before the following mock call.

If the execution order deviates from the order defined by the parallel context, the test validation fails. The method returns the full set of mock calls to allow combining them with other ordered setup methods.

func Setup

func Setup(fncalls ...func(*Mocks) any) func(*Mocks) any

Setup creates only a lazily ordered set of mock calls that is detached from the parent setup by returning no calls for chaining. The mock calls created by the setup are only validated in so far in relation to each other, that `gomock` delivers results for the same mock call receiver in the order provided during setup.

func Sub

func Sub(from, to int, fncall func(*Mocks) any) func(*Mocks) any

Sub returns the sub slice of mock calls starting at index `from` up to index `to` including. A negative value is used to calculate an index from the end of the slice. If the index of `from` is higher as the index `to`, the indexes are automatically switched. The returned sub slice of mock calls keeps its original semantic.

Types

type Call

type Call = gomock.Call

Call alias for gomock.Call.

type ConfigFunc added in v0.0.34

type ConfigFunc func(*Mocks)

ConfigFunc common mock handler configuration function signature.

func Context added in v0.0.34

func Context(context int) ConfigFunc

Context sets the number of context lines to show before and after changes in a diff. The default, 3, means no context lines.

func ContinueOnMethod added in v0.0.34

func ContinueOnMethod(enable bool) ConfigFunc

ContinueOnMethod sets whether or not recursion should continue once a custom error or `Stringer` interface is invoked. The default, false, means it will print the results of invoking the custom error or `Stringer` interface and return immediately instead of continuing to recurse into the internals of the data type.

*Note:* This flag does not have any effect if method invocation is disabled via the DisableMethods or DisablePointerMethods options.

func DisableCapacities added in v0.0.34

func DisableCapacities(disable bool) ConfigFunc

DisableCapacities sets whether to disable the printing of capacities for arrays, slices, maps and channels. This is useful when diffing data structures in tests.

func DisableMethods added in v0.0.34

func DisableMethods(disable bool) ConfigFunc

DisableMethods sets whether or not error and `Stringer` interfaces are invoked for types that implement them. Default is true, meaning that these methods will not be invoked.

func DisablePointerAddresses added in v0.0.34

func DisablePointerAddresses(disable bool) ConfigFunc

DisablePointerAddresses sets whether to disable the printing of pointer addresses. This is useful when diffing data structures in tests.

func DisablePointerMethods added in v0.0.34

func DisablePointerMethods(disable bool) ConfigFunc

DisablePointerMethods sets whether or not to check for and invoke error and `Stringer` interfaces on types which only accept a pointer receiver when the current type is not a pointer.

*Note:* This might be an unsafe action since calling one a pointer receiver could technically mutate the value. In practice, types which choose to satisfy an error or `Stringer` interface with a pointer receiver should not mutate their state inside these methods. As a result, this option relies on access to the unsafe package, so it will not have any effect when running in environments without access to the unsafe package such as Google App Engine or with the "safe" build tag specified.

func FromDate added in v0.0.34

func FromDate(date string) ConfigFunc

FromDate sets the label to use for the "from" date of the diff. Default is empty.

func FromFile added in v0.0.34

func FromFile(file string) ConfigFunc

FromFile sets the label to use for the "from" side of the diff. Default is `Want`.

func Indent added in v0.0.34

func Indent(indent string) ConfigFunc

Indent sets the string to use for each indentation level. The global config instance that all top-level functions use set this to a single space by default. If you would like more indentation, you might set this to a tab with `\t` or perhaps two spaces with ` `.

func MaxDepth added in v0.0.34

func MaxDepth(maxDepth int) ConfigFunc

MaxDepth sets the maximum number of levels to descend into nested data structures. The default 0 means there is no limit. Circular data structures are properly detected, so it is not necessary to set this value unless you specifically want to limit deeply nested structures.

func SortKeys added in v0.0.34

func SortKeys(sort bool) ConfigFunc

SortKeys sets whether map keys should be sorted before being printed. Use this to have a more deterministic, diffable output. Note that only native types (bool, int, uint, floats, uintptr and string) and types that support the error or `Stringer` interfaces (if methods are enabled) are supported, with other types sorted according to the reflect.Value.String() output which guarantees display stability.

func SpewKeys added in v0.0.34

func SpewKeys(spew bool) ConfigFunc

SpewKeys sets that, as a last resort attempt, map keys should be spewed to strings and sorted by those strings. This is only considered if keys are sorted (see `SortKeys`).

func ToDate added in v0.0.34

func ToDate(date string) ConfigFunc

ToDate specifies the label to use for the "to" date of the diff. Default is empty.

func ToFile added in v0.0.34

func ToFile(file string) ConfigFunc

ToFile sets the label to use for the "to" side of the diff. Default is `Got`.

type Controller

type Controller = gomock.Controller

Controller alias for gomock.Controller.

type DetachMode

type DetachMode int

DetachMode defines the mode for detaching mock calls.

const (
	// None mode to not detach mode.
	None DetachMode = 0
	// Head mode to detach head, i.e. do not order mock calls after predecessor
	// mock calls provided via context.
	Head DetachMode = 1
	// Tail mode to detach tail, i.e. do not order mock calls before successor
	// mock calls provided via context.
	Tail DetachMode = 2
	// Both mode to detach tail and head, i.e. do neither order mock calls after
	// predecessor nor before successor provided via context.
	Both DetachMode = 3
)

func (DetachMode) String

func (m DetachMode) String() string

String return string representation of detach mode.

type DiffConfig added in v0.0.49

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

DiffConfig holds configuration settings for matchers.

func NewDiffConfig added in v0.0.49

func NewDiffConfig() *DiffConfig

NewDiffConfig creates a new matcher configuration instance with default values.

func (*DiffConfig) Context added in v0.0.49

func (c *DiffConfig) Context(context int)

Context sets the number of context lines to show before and after changes in a diff. The default, 3, means no context lines.

func (*DiffConfig) ContinueOnMethod added in v0.0.49

func (c *DiffConfig) ContinueOnMethod(enable bool)

ContinueOnMethod sets whether or not recursion should continue once a custom error or `Stringer` interface is invoked. The default, false, means it will print the results of invoking the custom error or `Stringer` interface and return immediately instead of continuing to recurse into the internals of the data type.

*Note:* This flag does not have any effect if method invocation is disabled via the DisableMethods or DisablePointerMethods options.

func (*DiffConfig) Diff added in v0.0.49

func (c *DiffConfig) Diff(want, got any) string

Diff returns a diff of the expected value and the actual value as long as both are of the same type and are a struct, map, slice, array or string. Otherwise it returns an empty string.

func (*DiffConfig) DisableCapacities added in v0.0.49

func (c *DiffConfig) DisableCapacities(disable bool)

DisableCapacities sets whether to disable the printing of capacities for arrays, slices, maps and channels. This is useful when diffing data structures in tests.

func (*DiffConfig) DisableMethods added in v0.0.49

func (c *DiffConfig) DisableMethods(disable bool)

DisableMethods sets whether or not error and `Stringer` interfaces are invoked for types that implement them. Default is true, meaning that these methods will not be invoked.

func (*DiffConfig) DisablePointerAddresses added in v0.0.49

func (c *DiffConfig) DisablePointerAddresses(disable bool)

DisablePointerAddresses sets whether to disable the printing of pointer addresses. This is useful when diffing data structures in tests.

func (*DiffConfig) DisablePointerMethods added in v0.0.49

func (c *DiffConfig) DisablePointerMethods(disable bool)

DisablePointerMethods sets whether or not to check for and invoke error and `Stringer` interfaces on types which only accept a pointer receiver when the current type is not a pointer.

*Note:* This might be an unsafe action since calling one a pointer receiver could technically mutate the value. In practice, types which choose to satisfy an error or `Stringer` interface with a pointer receiver should not mutate their state inside these methods. As a result, this option relies on access to the unsafe package, so it will not have any effect when running in environments without access to the unsafe package such as Google App Engine or with the "safe" build tag specified.

func (*DiffConfig) FromDate added in v0.0.49

func (c *DiffConfig) FromDate(date string)

FromDate sets the label to use for the "from" date of the diff. Default is empty.

func (*DiffConfig) FromFile added in v0.0.49

func (c *DiffConfig) FromFile(file string)

FromFile sets the label to use for the "from" side of the diff. Default is `Want`.

func (*DiffConfig) Indent added in v0.0.49

func (c *DiffConfig) Indent(indent string)

Indent sets the string to use for each indentation level. The global config instance that all top-level functions use set this to a single space by default. If you would like more indentation, you might set this to a tab with `\t` or perhaps two spaces with ` `.

func (*DiffConfig) MaxDepth added in v0.0.49

func (c *DiffConfig) MaxDepth(maxDepth int)

MaxDepth sets the maximum number of levels to descend into nested data structures. The default 0 means there is no limit. Circular data structures are properly detected, so it is not necessary to set this value unless you specifically want to limit deeply nested structures.

func (*DiffConfig) SortKeys added in v0.0.49

func (c *DiffConfig) SortKeys(sort bool)

SortKeys sets map keys should be sorted before being printed. Use this to have a more deterministic, diffable output. Note that only native types (bool, int, uint, floats, uintptr and string) and types that support the error or `Stringer` interfaces (if methods are enabled) are supported, with other types sorted according to the reflect.Value.String() output which guarantees display stability.

func (*DiffConfig) SpewKeys added in v0.0.49

func (c *DiffConfig) SpewKeys(spew bool)

SpewKeys sets that, as a last resort attempt, map keys should be spewed to strings and sorted by those strings. This is only considered if keys are sorted (see `SortKeys`).

func (*DiffConfig) ToDate added in v0.0.49

func (c *DiffConfig) ToDate(date string)

ToDate sets the label to use for the "to" date of the diff. Default is empty.

func (*DiffConfig) ToFile added in v0.0.49

func (c *DiffConfig) ToFile(file string)

ToFile sets the label to use for the "to" side of the diff. Default is `Got`.

type Equal added in v0.0.34

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

Equal is an improved `gomock.Matcher` that matches via `reflect.DeepEqual` showing detailed diff when there is a mismatch.

func (*Equal) Got added in v0.0.34

func (eq *Equal) Got(got any) string

Got returns a string representation of the actual value.

func (*Equal) Matches added in v0.0.34

func (eq *Equal) Matches(got any) bool

Matches returns whether the actual value is equal to the expected value.

func (*Equal) String added in v0.0.34

func (eq *Equal) String() string

String returns a string representation of the expected value along with the diff between expected and actual values as long as both are of the same type and are a struct, map, slice, array or string. Otherwise the diff is hidden.

type Mocks

type Mocks struct {
	// The mock controller used.
	Ctrl *Controller
	// contains filtered or unexported fields
}

Mocks common mock handler.

func NewMocks

func NewMocks(t gomock.TestReporter, fncalls ...ConfigFunc) *Mocks

NewMocks creates a new mock handler using given test reporter, e.g. *testing.T, or [test.Test].

func (*Mocks) Add

func (mocks *Mocks) Add(delta int) int

Add adds the given delta on the wait group to register the expected or notify the consumed mock calls. This method implements the sync.WaitGroup interface to support testing of detached *goroutines* in an isolated [test](../test) environment.

**Note:** Usually call expectation setup is completely handled via `Call`, `Do`, `Return`, and `Panic`. Use this method only for synchronizing tests *goroutines*.

func (*Mocks) Call

func (mocks *Mocks) Call(fn any, call func(...any) []any) any

Call is a convenience method to setup a call back function for gomock.Do and gomock.DoAndReturn. Using this method signals an expected mock call during setup as well as a consumed mock call when executing the given call back function. The function is supplied with the regular call parameters and expected to return the mock result - if required, as gomock.Do ignores arguments.

**Note:** Call registers exactly one expected call automatically.

func (*Mocks) Config added in v0.0.34

func (mocks *Mocks) Config(fncalls ...ConfigFunc) *Mocks

Config configures the mock handler with given config functions.

func (*Mocks) Do

func (mocks *Mocks) Do(fn any, args ...any) any

Do is a convenience method to setup a call back function for gomock.Do or gomock.DoAndReturn. Using this method signals an expected mock call during setup as well as a consumed mock call when executing the given call back function returning the given optional arguments as mock result - if necessary, as gomock.Do ignores arguments.

**Note:** Do registers exactly one expected call automatically.

func (*Mocks) Done

func (mocks *Mocks) Done()

Done removes exactly one expected mock call from the wait group to notify a consumed mock call. This method implements the sync.WaitGroup interface to support testing of detached `go-routines` in an isolated [test](../test) environment.

**Note:** Usually call expectation setup is completely handled via `Call`, `Do`, `Return`, and `Panic`. Use this method only for synchronizing tests *goroutines*.

func (*Mocks) Equal added in v0.0.34

func (mocks *Mocks) Equal(want any) *Equal

Equal returns an improved equals matcher showing a detailed diff when there is a mismatch in the expected and actual values.

func (*Mocks) Expect

func (mocks *Mocks) Expect(fncalls SetupFunc) *Mocks

Expect configures the mock handler to expect the given mock function calls.

func (*Mocks) Get

func (mocks *Mocks) Get(creator reflect.Value) any

Get resolves the singleton mock from the mock handler by providing the reflection value of the constructor function generated by gomock to create a new mock. The mock is only created once and stored in an internal creator function to mock map.

func (*Mocks) GetArg

func (mocks *Mocks) GetArg(key any) any

GetArg gets the mock argument value for the given argument key. This can be used to access a common test arguments from a mock call.

func (*Mocks) GetMock added in v0.0.51

func (mocks *Mocks) GetMock(expect any) any

GetMock resolves the related mock from the mock handler, if the provided value is a mock constructor. Else the provided value is returned as is. This can be used to resolve optional mock expectations without breaking other test expectations.

func (*Mocks) Panic

func (mocks *Mocks) Panic(fn any, reason any) any

Panic is a convenience method to setup a call back function that panics with given reason for gomock.Do or gomock.DoAndReturn. Using this method signals an expected mock call during setup as well as a consumed mock call when executing the given call back function.

**Note:** Return registers exactly one expected call automatically.

func (*Mocks) Return

func (mocks *Mocks) Return(fn any, args ...any) any

Return is a convenience method to setup a call back function for gomock.Do or gomock.DoAndReturn. Using this method signals an expected mock call during setup as well as a consumed mock call when executing the given call back function returning the given optional arguments as mock result - if necessary, as gomock.Do ignores arguments.

**Note:** Return registers exactly one expected call automatically.

func (*Mocks) SetArg

func (mocks *Mocks) SetArg(key any, value any) *Mocks

SetArg sets the given mock argument value for the given argument key. This can be used to pass a common test arguments to mock calls.

func (*Mocks) SetArgs

func (mocks *Mocks) SetArgs(args map[any]any) *Mocks

SetArgs sets the given mock argument values for the given argument keys. This can be used to pass a set of common test arguments to mock calls.

func (*Mocks) Times

func (mocks *Mocks) Times(num int) int

Times is creating the expectation that exactly the given number of mock call are consumed. This call is supposed to be used as input for gomock.Times in combination with Call, [Do], [Return], and [Panic]. Setting up [Times] is considering that these methods add one expected call by reducing the registration by one.

func (*Mocks) Wait

func (mocks *Mocks) Wait()

Wait waits for all mock calls registered via Call, [Do], [Return], [Panic], and [Times] to be consumed before testing can continue. This method implements the sync.WaitGroup interface to support testing of detached *goroutines* in an isolated [test](../test) environment.

type SetupFunc

type SetupFunc func(*Mocks) any

SetupFunc common mock setup function signature.

Jump to

Keyboard shortcuts

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