mock

package module
v0.0.0-...-b114e0e Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2023 License: MIT Imports: 7 Imported by: 21

README

go-mock

A mocking framework for Go.

Read online reference at http://godoc.org/github.com/maraino/go-mock

Status

Build Status Coverage Status GoDoc

Usage

Let's say that we have an interface like this that we want to Mock.

type Client interface {
	Request(url *url.URL) (int, string, error)
}

We need to create a new struct that implements the interface. But we will use github.com/maraino/go-mock to replace the actual calls with some specific results.

import (
	"github.com/maraino/go-mock"
	"net/url"
)

type MyClient struct {
	mock.Mock
}

func (c *MyClient) Request(url *url.URL) (int, string, error) {
	ret := c.Called(url)
	return ret.Int(0), ret.String(1), ret.Error(2)
}

Then we need to configure the responses for the defined functions:

c := &MyClient{}
url, _ := url.Parse("http://www.example.org")
c.When("Request", url).Return(200, "{result:1}", nil).Times(1)

We will execute the function that we have Mocked:

code, json, err := c.Request(url)
fmt.Printf("Code: %d, JSON: %s, Error: %v\n", code, json, err)

This will produce the output:

Code: 200, JSON: {result:1}, Error: <nil>

And finally if we want to verify the number of calls we can use:

if ok, err := c.Verify(); !ok {
	fmt.Println(err)
}

API Reference

func (m *Mock) When(name string, arguments ...interface{}) *MockFunction

Creates an stub for a specific function and a list of arguments.

c.When("FunctionName", argument1, argument2, ...)

It returns a mock.MockFunction that can be used to configure the behavior and validations when the method is called

func (m *Mock) Reset() *Mock

Removes all the defined stubs and returns a clean mock.

func (m *Mock) Verify() (bool, error)

Checks all validations and return if true if they are ok, or false and an error if at least one validation have failed.

func (m *Mock) Called(arguments ...interface{}) *MockResult

Called must be used in the struct that implements the interface that we want to mock. It's the code that glues that struct with the go-mock package.

We will need to implement the interface and then use Called with the function arguments and use the return value to return the values to our mocked struct.

type Map interface {
	Set(key string, value interface{})
	Get(key string) (interface{}, error)
	GetString(key string) (string, error)
	Load(key string, value interface{}) error
}

type MyMap struct {
	mock.Mock
}

func (m *MyMap) Set(key string, value interface{}) {
	m.Called(key, value)
}

func (m *MyMap) Get(key string) (interface{}, error) {
	ret := m.Called(key)
	return ret.Get(0), ret.Error(1)
}

func (m *MyMap) GetString(key string) (string, error) {
	ret := m.Called(key)
	return ret.String(0), ret.Error(1)
}

func (m *MyMap) Load(key string, value interface{}) error {
	ret := m.Called(key, value)
	return ret.Error(0)
}
func (f *MockFunction) Return(v ...interface{}) *MockFunction

Defines the return parameters of our stub. The use of it is pretty simple, we can simply chain mock.When with Return to set the return values.

m.When("Get", "a-test-key").Return("a-test-value", nil)
m.When("GetString", "a-test-key").Return("a-test-value", nil)
m.When("Get", "another-test-key").Return(123, nil)
m.When("Get", mock.Any).Return(nil, errors.New("not-found"))

If no return values are set, the method will return 0 for numeric types, false for bools, "" for strings and nil for errors or any other type.

func (f *MockFunction) ReturnToArgument(n int, v interface{}) *MockFunction

Defines a special return parameter to an argument of the function. We can also chain this method to a When or a Return.

m.When("Load", "a-test-key").ReturnToArgument(1, "a-test-value")
m.When("Load", "another-test-key").Return(nil).ReturnToArgument(1, 123)
func (f *MockFunction) Panic(v interface{}) *MockFunction

Panic will cause a panic when the stub method is called with the specified parameters.

m.When("Get", "foobar").Panic("internal error")
func (f *MockFunction) Times(a int) *MockFunction

Defines the exact number of times a method should be called. This is validated if mock.Verify is executed.

m.When("Get", "a-test-key").Return("a-test-value", nil).Times(1)
func (f *MockFunction) AtLeast(a int) *MockFunction

Defines the minimum number of times a method should be called. This is validated if mock.Verify is executed.

m.When("Get", "a-test-key").Return("a-test-value", nil).AtLeast(2)
func (f *MockFunction) AtMost(a int) *MockFunction

Defines the maximum number of times a method should be called. This is validated if mock.Verify is executed.

m.When("Get", "a-test-key").Return("a-test-value", nil).AtMost(1)
func (f *MockFunction) Between(a, b int) *MockFunction

Defines a range of times a method should be called. This is validated if mock.Verify is executed.

m.When("Get", "a-test-key").Return("a-test-value", nil).Between(2, 5)
func (f *MockFunction) Timeout(d time.Duration) *MockFunction

Defines a timeout to sleep before returning the value of a function.

m.When("Get", "a-test-key").Return("a-test-value", nil).Timeout(100 * time.Millisecond)
func (f *MockFunction) Call(call interface{}) *MockFunction

Defines a custom function that will be executed instead of the function in the stub. The return values of the function will be used as the return values for the stub.

datastore := make(map[string]interface{})

m.When("Get", mock.Any).Call(func(key string) (interface{}, error) {
	if i, ok := datastore[key]; ok {
		return i, nil
	} else {
		return nil, ErrNotFound
	}
})

m.When("Set", mock.Any, mock.Any).Call(func(key string, value interface{}) error {
	datastore[key] = value
	return nil
})

Documentation

Overview

Package mock provides a mocking framework for Go.

https://github.com/maraino/go-mock

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertVerifyMocks

func AssertVerifyMocks(t HasError, mocks ...HasVerify)

Fail the test if any of the mocks fail verification

func VerifyMocks

func VerifyMocks(mocks ...HasVerify) (bool, error)

VerifyMocks verifies a list of mocks, and returns the first error, if any.

Types

type AnyIfType

type AnyIfType func(interface{}) bool

AnyIfType defines the type used as an argument that satisfies a condition.

func AnyIf

func AnyIf(f func(interface{}) bool) AnyIfType

AnyIf is a helper to define AnyIfType arguments.

Example:

f := func(i interface{}) bool {
	ii, ok := i.(MyType)
	return ok && ii.ID = "the-id"
}
mock.When("MyMethod", mock.AnyIf(f)).Return(0)

func Slice

func Slice(elements ...interface{}) AnyIfType

Slice is a helper to define AnyIfType arguments for slices and their elements.

Example:

mock.When("MyMethod", mock.Slice(123, mock.Rest)).Return(0)

type AnyType

type AnyType string

AnyType defines the type used as a replacement for any kind of argument in the stub configuration.

const (
	Any AnyType = "mock.any"
)

Any is the constant that should be used to represent a AnyType.

Example:

mock.When("MyMethod", mock.Any, mock.Any).Return(0)

type AnythingOfType

type AnythingOfType string

AnythingOfType defines the type used as a replacement for an argument of a specific type in the stub configuration.

func AnyOfType

func AnyOfType(t string) AnythingOfType

AnyOfType is a helper to define AnythingOfType arguments.

Example:

mock.When("MyMethod", mock.AnyOfType("int"), mock.AnyOfType("string")).Return(0)

type HasError

type HasError interface {
	Error(...interface{})
}

Used to represent a test we can fail, without importing the testing package Importing "testing" in a file not named *_test.go results in tons of test.* flags being added to any compiled binary including this package

type HasVerify

type HasVerify interface {
	Verify() (bool, error)
}

HasVerify is used as the input of VerifyMocks (Mock satisfies it, obviously)

type Mock

type Mock struct {
	Functions []*MockFunction
	// contains filtered or unexported fields
}

Mock should be embedded in the struct that we want to act as a Mock.

Example:

type MyClient struct {
	mock.Mock
}

func (*Mock) Called

func (m *Mock) Called(arguments ...interface{}) *MockResult

Called is the function used in the mocks to replace the actual task.

Example:

func (m *MyClient) Request(url string) (int, string, error) {
	r := m.Called(url)
	return r.Int(0), r.String(1), r.Error(2)
}

func (*Mock) Reset

func (m *Mock) Reset() *Mock

Reset removes all stubs defined.

func (*Mock) Verify

func (m *Mock) Verify() (bool, error)

Verify verifies the restrictions set in the stubbing.

func (*Mock) When

func (m *Mock) When(name string, arguments ...interface{}) *MockFunction

When defines an stub of one method with some specific arguments. It returns a *MockFunction that can be configured with Return, ReturnToArgument, Panic, ...

type MockCountCheckType

type MockCountCheckType int
const (
	NONE MockCountCheckType = iota
	TIMES
	AT_LEAST
	AT_MOST
	BETWEEN
)

type MockFunction

type MockFunction struct {
	Name              string
	Arguments         []interface{}
	ReturnValues      []interface{}
	ReturnToArguments []MockReturnToArgument
	PanicValue        interface{}
	// contains filtered or unexported fields
}

MockFunction is the struct used to store the properties of a method stub.

func (*MockFunction) AtLeast

func (f *MockFunction) AtLeast(a int) *MockFunction

AtLeast defines the number of times that a *MockFunction must be at least called. This is verified if mock.Verify is called.

func (*MockFunction) AtMost

func (f *MockFunction) AtMost(a int) *MockFunction

AtMost defines the number of times that a *MockFunction must be at most called. This is verified if mock.Verify is called.

func (*MockFunction) Between

func (f *MockFunction) Between(a, b int) *MockFunction

Between defines a range of times that a *MockFunction must be called. This is verified if mock.Verify is called.

func (*MockFunction) Call

func (f *MockFunction) Call(call interface{}) *MockFunction

Call executes a function passed as an argument using the arguments pased to the stub. If the function returns any output parameters they will be used as a return arguments when the stub is called. If the call argument is not a function it will panic when the stub is executed.

Example:

mock.When("MyMethod", mock.Any, mock.Any).Call(func(a int, b int) int {
	return a+b
})

func (*MockFunction) Panic

func (f *MockFunction) Panic(v interface{}) *MockFunction

Panic defines a panic for a specific *MockFunction.

func (*MockFunction) Return

func (f *MockFunction) Return(v ...interface{}) *MockFunction

Return defines the return values of a *MockFunction.

func (*MockFunction) ReturnToArgument

func (f *MockFunction) ReturnToArgument(n int, v interface{}) *MockFunction

ReturnToArgument defines the values returned to a specific argument of a *MockFunction.

func (*MockFunction) Timeout

func (f *MockFunction) Timeout(d time.Duration) *MockFunction

Timeout defines a timeout to sleep before returning the value of a function.

func (*MockFunction) Times

func (f *MockFunction) Times(a int) *MockFunction

Times defines how many times a *MockFunction must be called. This is verified if mock.Verify is called.

type MockResult

type MockResult struct {
	Result []interface{}
}

MockResult struct is used to store the return arguments of a method stub.

func (*MockResult) Bool

func (r *MockResult) Bool(i int) bool

Bool returns a specific return parameter as a bool. If a result has not been set, it returns false.

func (*MockResult) Byte

func (r *MockResult) Byte(i int) byte

Byte returns a specific return parameter as a byte. If a result has not been set, it returns 0.

func (*MockResult) Bytes

func (r *MockResult) Bytes(i int) []byte

Bytes returns a specific return parameter as a []byte. If a result has not been set, it returns nil.

func (*MockResult) Contains

func (r *MockResult) Contains(i int) bool

Contains returns true if the results have the index i, false otherwise.

func (*MockResult) Error

func (r *MockResult) Error(i int) error

Error returns a specific return parameter as an error. If a result has not been set, it returns nil.

func (*MockResult) Float32

func (r *MockResult) Float32(i int) float32

Float32 returns a specific return parameter as a float32. If a result has not been set, it returns 0.

func (*MockResult) Float64

func (r *MockResult) Float64(i int) float64

Float64 returns a specific return parameter as a float64. If a result has not been set, it returns 0.

func (*MockResult) Get

func (r *MockResult) Get(i int) interface{}

Get returns a specific return parameter. If a result has not been set, it returns nil,

func (*MockResult) GetType

func (r *MockResult) GetType(i int, ii interface{}) interface{}

GetType returns a specific return parameter with the same type of the second argument. A nil version of the type can be casted without causing a panic.

func (*MockResult) Int

func (r *MockResult) Int(i int) int

Int returns a specific return parameter as an int. If a result has not been set, it returns 0.

func (*MockResult) Int16

func (r *MockResult) Int16(i int) int16

Int16 returns a specific return parameter as an int16. If a result has not been set, it returns 0.

func (*MockResult) Int32

func (r *MockResult) Int32(i int) int32

Int32 returns a specific return parameter as an int32. If a result has not been set, it returns 0.

func (*MockResult) Int64

func (r *MockResult) Int64(i int) int64

Int64 returns a specific return parameter as an int64. If a result has not been set, it returns 0.

func (*MockResult) Int8

func (r *MockResult) Int8(i int) int8

Int8 returns a specific return parameter as an int8. If a result has not been set, it returns 0.

func (*MockResult) String

func (r *MockResult) String(i int) string

String returns a specific return parameter as a string. If a result has not been set, it returns "".

type MockReturnToArgument

type MockReturnToArgument struct {
	Argument int
	Value    interface{}
}

MockReturnToArgument defines the function arguments used as return parameters.

type RestType

type RestType string

RestType indicates there may optionally be one or more remaining elements.

const Rest RestType = "mock.rest"

Rest indicates there may optionally be one or more remaining elements.

Example:

mock.When("MyMethod", mock.Slice(123, mock.Rest)).Return(0)

Jump to

Keyboard shortcuts

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