Documentation
¶
Overview ¶
Package mock provides helpers for creating and testing with interface mocks.
Index ¶
- Constants
- Variables
- func AnySlice(cnt int) []any
- func WithNoStack(mck *Mock)
- type Arguments
- func (args Arguments) Bool(idx int) bool
- func (args Arguments) Diff(vs []any) ([]string, int)
- func (args Arguments) Equal(haves ...any) bool
- func (args Arguments) Error(idx int) error
- func (args Arguments) Get(idx int) any
- func (args Arguments) Int(idx int) int
- func (args Arguments) String(idx int) string
- type Call
- func (c *Call) After(d time.Duration) *Call
- func (c *Call) Alter(fn ...func(Arguments)) *Call
- func (c *Call) CanCall() error
- func (c *Call) End() *Mock
- func (c *Call) Once() *Call
- func (c *Call) Optional() *Call
- func (c *Call) Panic(value any) *Call
- func (c *Call) Requires(calls ...*Call) *Call
- func (c *Call) Return(args ...any) *Call
- func (c *Call) Satisfied() bool
- func (c *Call) Times(i int) *Call
- func (c *Call) Until(ch <-chan time.Time) *Call
- func (c *Call) With(args ...any) *Call
- type Matcher
- type Mock
- func (mck *Mock) AssertCallCount(method string, want int) bool
- func (mck *Mock) AssertExpectations() bool
- func (mck *Mock) Call(method string, args ...any) Arguments
- func (mck *Mock) Callable(method string, args ...any) error
- func (mck *Mock) Called(args ...any) Arguments
- func (mck *Mock) Failed() bool
- func (mck *Mock) GetData() map[string]any
- func (mck *Mock) On(method string, args ...any) *Call
- func (mck *Mock) OnAny(method string) *Call
- func (mck *Mock) Proxy(met any, name ...string) *Call
- func (mck *Mock) SetData(data map[string]any)
- func (mck *Mock) Unset(remove *Call) *Mock
- type Option
Constants ¶
const ( // Any is used in Diff and Assert when the argument being tested // shouldn't be taken into consideration. Any = "mock.Any" )
Variables ¶
var ( // ErrNeverCalled signals mocked non-optional method was never called. ErrNeverCalled = errors.New("method never called") // ErrTooFewCalls signals mocked method was called too few times. ErrTooFewCalls = errors.New("method called to few times") // ErrTooManyCalls signals mocked method was called too many times. ErrTooManyCalls = errors.New("method called too many times") // ErrRequirements signals mocked method requirements were not met. ErrRequirements = errors.New("method requirements not met") // ErrNotFound signals mocked method has not been found. ErrNotFound = errors.New("method not found") )
Mock requirements violations.
var AnyBool = MatchOfType("bool")
AnyBool is a helper matching any argument value of boolean type.
AnyCtx matches any non-nil context.
var AnyInt = MatchOfType("int")
AnyInt is a helper matching any argument value of integer type.
var AnyString = MatchOfType("string")
AnyString is a helper matching any argument value of string type.
Functions ¶
func WithNoStack ¶
func WithNoStack(mck *Mock)
WithNoStack is option for NewMock turning off displaying stack traces in error log messages.
Types ¶
type Arguments ¶
type Arguments []any
Arguments holds an array of method arguments or return values.
func (Arguments) Bool ¶
Bool gets the argument at the specified index. Panics if there is no argument, or if the argument is of the wrong type.
func (Arguments) Diff ¶
Diff gets a string describing the differences between the expected arguments and the specified values. Returns a diff string and number of differences found.
nolint: cyclop
func (Arguments) Equal ¶
Equal gets whether the objects match the specified arguments. Panics on error.
func (Arguments) Error ¶
Error gets the argument at the specified index. Panics if there is no argument, or if the argument is of the wrong type.
func (Arguments) Get ¶
Get returns the argument at the specified index. Panics when index is out of bounds.
func (Arguments) Int ¶
Int gets the argument at the specified index cast to int. Panics for invalid index or when argument cannot be cast to an int.
type Call ¶
type Call struct {
// contains filtered or unexported fields
}
Call represents a mocked method call, used for defining expectations.
func (*Call) After ¶
After sets how long to block until the call returns.
Mock.On("Method", arg1, arg2).After(time.Second)
func (*Call) Alter ¶
Alter sets functions to be called on arguments received by the mocked method before they are returned. It can be used when mocking a method (such as an unmarshaler) that takes a pointer to a struct and sets properties in such struct.
Example usage:
Mock.On("Unmarshal", MatchOfType("map[string]any")). Return(). Alter(func(args Arguments) { arg := args.Get(0).(*map[string]any) arg["foo"] = "bar" })
If Call.After or Call.Until methods are used, the provided function is run after the blocking is done.
func (*Call) CanCall ¶
CanCall provided the argument match returns nil if the method can be called again, otherwise it returns error explaining why method cannot be called.
func (*Call) Once ¶
Once specifies that the mocked method should only be called once with this set of arguments and return values. It is a helper calling Call.Times.
Example usage:
Mock.On("Method", arg1, arg2).Return(returnArg1, returnArg2).Once()
func (*Call) Optional ¶
Optional allows the method call to be optional, meaning that the method may or may not be invoked without causing test failures. This can be useful for scenarios where some method calls are not strictly required. Invoking the method after Call.Times will cause a panic as the two are mutually exclusive.
Example usage:
Mock.On("MethodName").Optional()
func (*Call) Panic ¶
Panic sets the panic value for the mock call and ensures that the method call will cause a panic during execution. This is useful for simulating failure scenarios where a panic is expected during a method call. It will panic if the Call instance represents a proxy call.
Example usage:
Mock.On("MethodName").Panic("test panic") Mock.On("MethodName").Panic(errors.New("test panic"))
func (*Call) Requires ¶
Requires specifies that the current call depends on other calls being satisfied. It's used to define prerequisite calls that need to be executed before this call. The referenced calls may be from the same mock instance and/or other mock instances.
Example usage:
other := Mock.On("Init").Return(nil) Mock.On("Do").Return(nil).Requires(other)
func (*Call) Return ¶
Return specifies the expected return arguments when the mocked method is invoked. If the Call instance represents a proxy call, this method will panic, as proxy calls cannot have predefined return values.
Example usage:
Mock.On("Method").Return(errors.New("operation failed"))
func (*Call) Satisfied ¶
Satisfied returns true if the method call requirements are met.
A method call is considered satisfied if:
- It has been called the exact number of requested times.
- It has no maximum call limit and has been called at least once.
- It has not been called, but is marked as optional.
func (*Call) Times ¶
Times specify that the mocked method should only be called i times with this set of arguments and return values.
Mock.On("Method", arg1, arg2).Return(returnArg1, returnArg2).Times(5)
func (*Call) Until ¶
Until sets a channel that will block the return of the method call until the channel is either closed or a message is received. This is useful for scenarios where delaying the method's return until certain conditions are met is required.
Example usage:
Mock.On("Method", arg1, arg2).Until(time.After(time.Second))
type Matcher ¶
type Matcher struct {
// contains filtered or unexported fields
}
Matcher represents argument matcher.
func MatchBy ¶
MatchBy constructs an Matcher instance which validates arguments using a given function. The function must be accepting a single argument (of the expected type) and return a true if argument matches expectations or false when it doesn't. If function doesn't match the required signature, MatchBy panics.
Examples:
fn := func(have int) bool { ... } fn := func(have float64) bool { ... } fn := func(have ExampleItf) bool { ... } fn := func(have ExampleType) bool { ... } fn := func(have *ExampleType) bool { ... }
MatchBy can be used to match complex mocked method argument like function, structure, channel, map, ...
Example:
MatchBy(func(req *http.Request) bool { return req.Host == "localhost" })
func MatchError ¶
MatchError creates an Matcher that verifies the argument is a non-nil error. The "want" parameter specifies the expected error behavior:
- If want is a string, the error's message (via Error()) is matched.
- If want is an error, errors.Is is used to check.
It will panic if "want" is neither.
func MatchErrorContain ¶
MatchErrorContain constructs an argument matcher (Matcher) instance which ensures argument is a non nil error with given message.
func MatchOfType ¶
MatchOfType constructs an argument matcher (Matcher) instance which ensures argument is of given type.
Examples:
MatchOfType("int") MatchOfType("string") MatchOfType("mock.ExampleType") MatchOfType("*mock.ExampleType") MatchOfType("map[string]interface {}")
The MatchOfType will not match if the string is an interface name.
func MatchSame ¶
MatchSame matches two generic pointers point to the same object using [is.SamePointers].
func MatchType ¶
MatchType constructs an argument matcher (Matcher) instance which ensures argument is of the same type as the MatchType argument.
Examples:
MatchType(42) MatchType(true) MatchType("string") MatchType(mock.ExampleType{}) MatchType(*mock.ExampleType{})
func NewMatcher ¶
NewMatcher returns new instance of an Matcher. Takes a function as in MatchBy documentation and argument matcher description. Function panics on error.
type Mock ¶
type Mock struct {
// contains filtered or unexported fields
}
Mock tracks activity on a mocked interface.
func (*Mock) AssertCallCount ¶
AssertCallCount asserts the method was called "want" number of times.
func (*Mock) AssertExpectations ¶
AssertExpectations asserts that everything specified with Mock.On and Call.Return was in fact called as expected. Calls may have occurred in any order.
func (*Mock) Call ¶
Call calls method on the mock with arguments and returns the mocked method Arguments. Panics if the call is unexpected (i.e. not preceded by appropriate Mock.On calls). Blocks before returning if Call.Until or Call.After were used.
func (*Mock) Callable ¶
Callable finds a callable method with given name and matching arguments. When found it returns it, otherwise it returns an error describing the reason. Note that there may be more methods in the expected slice matching the criteria in which case the first one is returned.
A callable method is one that returns no error from Call.CanCall method, and has matching arguments.
func (*Mock) Called ¶
Called records that a method was invoked with the given arguments and returns the configured return values as a Arguments slice. It panics if the call is unexpected, meaning no matching Mock.On or Mock.OnAny expectation was set.
If the expectation uses Call.Until or Call.After, this method blocks until the specified condition is met.
func (*Mock) On ¶
On adds method call expectation for the interface being mocked.
Example usage:
Mock.On("Method", 1).Return(nil) Mock.On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error"))
func (*Mock) OnAny ¶
OnAny adds a method call expectation for the mocked interface. Unlike Mock.On, where specific arguments are expected, this allows the method to be called with any combination of arguments, regardless of their number or type.
Example usage:
Mock.OnAny("Method").Return(nil)
func (*Mock) Proxy ¶
Proxy uses passed method as a proxy for calls to its "name". If "name" argument is not empty the first value from the slice will be used as the proxied method name. It panics if "met" is not a method or function.
Example:
obj := &types.TPtr{} mck.Proxy(obj.Method)