pegomock

package module
v4.0.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2023 License: Apache-2.0 Imports: 12 Imported by: 14

README

Unit tests

logo

PegoMock is a mocking framework for the Go programming language. It integrates well with Go's built-in testing package, but can be used in other contexts too. It is based on golang/mock, but uses a DSL closely related to Mockito.

Installing Pegomock

Pegomock consists of a binary pegomock and a package. Install both via:

go install github.com/petergtz/pegomock/v4/pegomock@latest
go get github.com/petergtz/pegomock/v4@latest

This will download the package and install an executable pegomock in the directory named by the $GOBIN environment variable, which defaults to $GOPATH/bin or $HOME/go/bin if the $GOPATH environment variable is not set.

The pegomock binary is used to generate mocks and to watch over changes in interfaces. The package is used in your tests to create and verify mocks.

See also section Tracking the pegomock tool in your project for a per-project control of the tool version.

For migration from Pegomock v1/v2 to v3, see Migration notes in v3 release description.

Getting Started

Using Pegomock with Golang’s XUnit-style Tests

The preferred way is:

import (
	"github.com/petergtz/pegomock/v4"
	"testing"
)

func TestUsingMocks(t *testing.T) {
	mock := NewMockPhoneBook(pegomock.WithT(t))

	// use your mock here
}

Alternatively, you can set a global fail handler within your test:

func TestUsingMocks(t *testing.T) {
	pegomock.RegisterMockTestingT(t)

	mock := NewMockPhoneBook()

	// use your mock here
}

Note: In this case, Pegomock uses a global (singleton) fail handler. This has the benefit that you don’t need to pass the fail handler down to each test, but does mean that you cannot run your XUnit style tests in parallel with Pegomock.

If you configure both a global fail handler and a specific one for your mock, the specific one overrides the global fail handler.

Using Pegomock with Ginkgo

When a Pegomock verification fails, it calls a FailHandler. This is a function that you must provide using pegomock.RegisterMockFailHandler().

If you’re using Ginkgo, all you need to do is:

pegomock.RegisterMockFailHandler(ginkgo.Fail)

before you start your test suite.

Avoiding Ginkgo Naming Collision with When Function

Ginkgo introduced a new keyword in its DSL: When. This causes name collisions when dot-importing both Ginkgo and Pegomock. To avoid this, you can use a different dot-import for Pegomock which uses Whenever instead of When. Example:

package some_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/petergtz/pegomock/v4/ginkgo_compatible"
)

var _ = Describe("Some function", func() {
	When("certain condition", func() {
		It("succeeds", func() {
			mock := NewMockPhoneBook()
			Whenever(mock.GetPhoneNumber(Eq("Tom"))).ThenReturn("123-456-789")
		})
	})
})

Generating Your First Mock and Using It

Let's assume you have:

type Display interface {
	Show(text string)
}

The simplest way is to call pegomock from within your go package specifying the interface by its name:

cd path/to/package
pegomock generate Display

This will generate a mock_display_test.go file which you can now use in your tests:

// creating mock
display := NewMockDisplay()

// using the mock
display.Show("Hello World!")

// verifying
display.VerifyWasCalledOnce().Show("Hello World!")

Why yet Another Mocking Framework for Go?

I've looked at some of the other frameworks, but found none of them satisfying:

  • GoMock seemed overly complicated when setting up mocks and verifying them. The command line interface is also not quite intuitive. That said, Pegomock is based on the GoMock, reusing mostly the mockgen code.

  • Counterfeiter uses a DSL that I didn't find expressive enough. It often seems to need more lines of code too. In one of its samples, it uses e.g.:

    fake.DoThings("stuff", 5)
    Expect(fake.DoThingsCallCount()).To(Equal(1))
    
    str, num := fake.DoThingsArgsForCall(0)
    Expect(str).To(Equal("stuff"))
    Expect(num).To(Equal(uint64(5)))
    

    In Pegomock, this can be written as simple as:

    fake.DoThings("stuff", 5)
    fake.VerifyWasCalledOnce().DoThings("stuff", 5)
    

In addition, Pegomock provides a "watch" command similar to Ginkgo, which constantly watches over changes in an interface and updates its mocks. It gives the framework a much more dynamic feel, similar to mocking frameworks in Ruby or Java.

Using Mocks In Your Tests

Verifying Behavior

Interface:

type Display interface {
	Show(text string)
}

Test:

// creating mock:
display := NewMockDisplay()

// using the mock:
display.Show("Hello World!")

// verifying:
display.VerifyWasCalledOnce().Show("Hello World!")

Stubbing

Interface:

type PhoneBook interface {
	GetPhoneNumber(name string) string
}

Test:

// creating the mock
phoneBook := NewMockPhoneBook()

// stubbing:
When(phoneBook.GetPhoneNumber("Tom")).ThenReturn("345-123-789")
When(phoneBook.GetPhoneNumber("Invalid")).ThenPanic("Invalid Name")

// prints "345-123-789":
fmt.Println(phoneBook.GetPhoneNumber("Tom"))

// panics:
fmt.Println(phoneBook.GetPhoneNumber("Invalid"))

// prints "", because GetPhoneNumber("Dan") was not stubbed
fmt.Println(phoneBook.GetPhoneNumber("Dan"))

// Although it is possible to verify a stubbed invocation, usually it's redundant
// If your code cares what GetPhoneNumber("Tom") returns, then something else breaks (often even before a verification gets executed).
// If your code doesn't care what GetPhoneNumber("Tom") returns, then it should not be stubbed.

// Not convinced? See http://monkeyisland.pl/2008/04/26/asking-and-telling.
phoneBook.VerifyWasCalledOnce().GetPhoneNumber("Tom")
  • By default, for all methods that return a value, a mock will return zero values.
  • Once stubbed, the method will always return a stubbed value, regardless of how many times it is called.
  • ThenReturn supports chaining, i.e. ThenReturn(...).ThenReturn(...) etc. The mock will return the values in the same order the chaining was done. The values from the last ThenReturn will be returned indefinitely when the number of call exceeds the ThenReturns.

Stubbing Functions That Have no Return Value

Stubbing functions that have no return value requires a slightly different approach, because such functions cannot be passed directly to another function. However, we can wrap them in an anonymous function:

// creating mock:
display := NewMockDisplay()

// stubbing
When(func() { display.Show("Hello World!") }).ThenPanic("Panicking")

// panics:
display.Show("Hello World!")

Argument Matchers

Pegomock provides matchers for stubbing and verification.

Verification:

display := NewMockDisplay()

// Calling mock
display.Show("Hello again!")

// Verification:
display.VerifyWasCalledOnce().Show(AnyString())

Stubbing:

phoneBook := NewMockPhoneBook()

// Stubbing:
When(phoneBook.GetPhoneNumber(AnyString())).ThenReturn("123-456-789")

// Prints "123-456-789":
fmt.Println(phoneBook.GetPhoneNumber("Dan"))
// Also prints "123-456-789":
fmt.Println(phoneBook.GetPhoneNumber("Tom"))

Important: When you use argument matchers, you must always use them for all arguments:

// Incorrect, panics:
When(contactList.getContactByFullName("Dan", AnyString())).thenReturn(Contact{...})
// Correct:
When(contactList.getContactByFullName(Eq("Dan"), AnyString())).thenReturn(Contact{...})

Matching custom types:

type SearchQuery struct { ... }

When(contactList.searchContacts(Eq(SearchQuery{...}))).thenReturn([]Contact{...})

When(contactList.searchContacts(Any[SearchQuery]())).thenReturn([]Contact{...})

Verifying the Number of Invocations

display := NewMockDisplay()

// Calling mock
display.Show("Hello")
display.Show("Hello, again")
display.Show("And again")

// Verification:
display.VerifyWasCalled(Times(3)).Show(AnyString())
// or:
display.VerifyWasCalled(AtLeast(3)).Show(AnyString())
// or:
display.VerifyWasCalled(Never()).Show("This one was never called")

Verifying in Order

display1 := NewMockDisplay()
display2 := NewMockDisplay()

// Calling mocks
display1.Show("One")
display1.Show("Two")
display2.Show("Another two")
display1.Show("Three")

// Verification:
inOrderContext := new(InOrderContext)
display1.VerifyWasCalledInOrder(Once(), inOrderContext).Show("One")
display2.VerifyWasCalledInOrder(Once(), inOrderContext).Show("Another two")
display1.VerifyWasCalledInOrder(Once(), inOrderContext).Show("Three")

Note that it's not necessary to verify the call for display.Show("Two") if that one is not of any interested. An InOrderContext only verifies that the verifications that are done, are in order.

Stubbing with Callbacks

phoneBook := NewMockPhoneBook()

// Stubbing:
When(phoneBook.GetPhoneNumber(AnyString())).Then(func(params []Param) ReturnValues {
	return []ReturnValue{fmt.Sprintf("1-800-CALL-%v", strings.ToUpper(params[0]))}
},


// Prints "1-800-CALL-DAN":
fmt.Println(phoneBook.GetPhoneNumber("Dan"))
// Prints "1-800-CALL-TOM":
fmt.Println(phoneBook.GetPhoneNumber("Tom"))

Verifying with Argument Capture

In some cases it can be useful to capture the arguments from mock invocations and assert on them separately. This method is only recommended if the techniques using matchers are not sufficient.

display := NewMockDisplay()

// Calling mock
display.Show("Hello")
display.Show("Hello, again")
display.Show("And again")

// Verification and getting captured arguments
text := display.VerifyWasCalled(AtLeast(1)).Show(AnyString()).GetCapturedArguments()

// Captured arguments are from last invocation
Expect(text).To(Equal("And again"))

You can also get all captured arguments:

// Verification and getting all captured arguments
texts := display.VerifyWasCalled(AtLeast(1)).Show(AnyString()).GetAllCapturedArguments()

// Captured arguments are a slice
Expect(texts).To(ConsistOf("Hello", "Hello, again", "And again"))

Verifying with Asynchronous Mock Invocations

When the code exercising the mock is run as part of a Goroutine, it's necessary to verify in a polling fashion until a timeout kicks in. VerifyWasCalledEventually can help here:

display := NewMockDisplay()

go func() {
	doSomething()
	display.Show("Hello")
}()

display.VerifyWasCalledEventually(Once(), 2*time.Second).Show("Hello")

The Pegomock CLI

Installation

Install it via:

go install github.com/petergtz/pegomock/v4/pegomock@latest

Tracking the pegomock tool in your project

Go modules allow to pin not only a package but also a tool (that is, an executable). The steps are:

  1. Use a file named tools.go with contents similar to this:
// +build tools

// This file will never be compiled (see the build constraint above); it is
// used to record dependencies on build tools with the Go modules machinery.
// See https://github.com/go-modules-by-example/index/blob/master/010_tools/README.md

package tools

import (
	_ "github.com/petergtz/pegomock/v4/pegomock"
)
  1. Set $GOBIN to a bin directory relative to your repo (this defines where tool dependencies will be installed).
  2. Install the tool with go install:
$ cd /path/to/myproject
$ export GOBIN=$PWD/bin
$ go install github.com/petergtz/pegomock/v4/pegomock
  1. Use that $GOBIN when invoking pegomock for that project:
$ $GOBIN/pegomock ...

or

$ export PATH=$GOBIN:$PATH
$ pegomock ...

See Tools as dependencies for details.

Generating Mocks

To generate mocks, invoke Pegomock like this:

pegomock generate [<flags>] [<packagepath>] <interfacename>

Flags can be any of the following:

  • --output,-o: Output file; defaults to mock__test.go.

  • --package: Package of the generated code; defaults to the package from which pegomock was executed suffixed with _test

For more flags, run:

pegomock --help

Generating Mocks with --use-experimental-model-gen

There are a number of shortcomings in the current reflection-based implementation. To overcome these, there is now an option to use a new, experimental implementation that is based on golang.org/x/tools/go/loader. To use it when generating your mocks, invoke pegomock like this:

pegomock generate --use-experimental-model-gen [<flags>] [<packagepath>] <interfacename>

What are the benefits?

  • The current default uses the reflect package to introspect the interface for which a mock should be generated. But reflection cannot determine method parameter names, only types. This forces the generator to generate them based on a pattern. In a code editor with code assistence, those pattern-based names (such as _param0, _param1) are non-descriptive and provide less help while writing code. The new implementation properly parses the source (including all dependent packages) and subsequently uses the same names as used in the interface definition.
  • With the current default you cannot generate an interface that lives in the main package. It's due to the way this implementation works: it imports the interface's package into temporarily generated code that gets compiled on the fly. This compilation fails, because there are now two main functions.
  • The new implementation is simpler and will probably become the default in the future, because it will be easier to maintain.

What are the drawbacks?

  • There is only one drawback: maturity. The new implementation is not complete yet, and also might have some bugs that still need to be fixed.

Users of Pegomock are encouraged to use this new option and report any problems by opening an issue. Help to stabilize it is greatly appreciated.

Generating mocks with go generate

pegomock can be used with go generate. Simply add the directive to your source file.

Here's an example for a Display interface used by a calculator program:

// package/path/to/display/display.go

package display

type Display interface {
	Show(text string)
}
// package/path/to/calculator/calculator_test.go

package calculator_test

//go:generate pegomock generate package/path/to/display Display

// Use generated mock
mockDisplay := NewMockDisplay()
...

Generating it:

cd package/path/to/calculator
go generate

Note: While you could add the directive adjacent to the interface definition, the author's opinion is that this violates clean dependency management and would pollute the package of the interface. It's better to generate the mock in the same package, where it is used (if this coincides with the interface package, that's fine). That way, not only stays the interface's package clean, the tests also don't need to prefix the mock with a package, or use a dot-import.

Continuously Generating Mocks

The watch command lets Pegomock generate mocks continuously on every change to an interface:

pegomock watch

For this, Pegomock expects an interfaces_to_mock file in the package directory where the mocks should be generated. In fact, pegomock watch will create it for you if it doesn't exist yet. The contents of the file are similar to the ones of the generate command:

# Any line starting with a # is treated as comment.

# interface name without package specifies an Interface in the current package:
PhoneBook

 # generates a mock for SomeInterfacetaken from mypackage:
path/to/my/mypackage SomeInterface

# you can also specify a Go file:
display.go

# and use most of the flags from the "generate" command
--output my_special_output.go MyInterface

Flags can be:

  • --recursive,-r: Recursively watch sub-directories as well.

Removing Generated Mocks

Sometimes it can be useful to systematically remove all mocks and matcher files generated by Pegomock. For this purpose, there is the remove command. By simply calling it from the current directory

pegomock remove

it will remove all Pegomock-generated files in the current directory. It supports additional flags, such as --recursive to recursively remove all Pegomock-generated files in sub-directories as well. To see all possible options, run:

pegomock remove --help

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Any

func Any[T any]() T

func AnyBool deprecated

func AnyBool() bool

Deprecated: Use Any[T any]() instead.

func AnyBoolSlice deprecated

func AnyBoolSlice() []bool

Deprecated: Use Any[T any]() instead.

func AnyComplex128 deprecated

func AnyComplex128() complex128

Deprecated: Use Any[T any]() instead.

func AnyComplex128Slice deprecated

func AnyComplex128Slice() []complex128

Deprecated: Use Any[T any]() instead.

func AnyComplex64 deprecated

func AnyComplex64() complex64

Deprecated: Use Any[T any]() instead.

func AnyComplex64Slice deprecated

func AnyComplex64Slice() []complex64

Deprecated: Use Any[T any]() instead.

func AnyFloat32 deprecated

func AnyFloat32() float32

Deprecated: Use Any[T any]() instead.

func AnyFloat32Slice deprecated

func AnyFloat32Slice() []float32

Deprecated: Use Any[T any]() instead.

func AnyFloat64 deprecated

func AnyFloat64() float64

Deprecated: Use Any[T any]() instead.

func AnyFloat64Slice deprecated

func AnyFloat64Slice() []float64

Deprecated: Use Any[T any]() instead.

func AnyInt deprecated

func AnyInt() int

Deprecated: Use Any[T any]() instead.

func AnyInt16 deprecated

func AnyInt16() int16

Deprecated: Use Any[T any]() instead.

func AnyInt16Slice deprecated

func AnyInt16Slice() []int16

Deprecated: Use Any[T any]() instead.

func AnyInt32 deprecated

func AnyInt32() int32

Deprecated: Use Any[T any]() instead.

func AnyInt32Slice deprecated

func AnyInt32Slice() []int32

Deprecated: Use Any[T any]() instead.

func AnyInt64 deprecated

func AnyInt64() int64

Deprecated: Use Any[T any]() instead.

func AnyInt64Slice deprecated

func AnyInt64Slice() []int64

Deprecated: Use Any[T any]() instead.

func AnyInt8 deprecated

func AnyInt8() int8

Deprecated: Use Any[T any]() instead.

func AnyInt8Slice deprecated

func AnyInt8Slice() []int8

Deprecated: Use Any[T any]() instead.

func AnyIntSlice deprecated

func AnyIntSlice() []int

Deprecated: Use Any[T any]() instead.

func AnyInterface deprecated

func AnyInterface() interface{}

Deprecated: Use Any[T any]() instead.

func AnyInterfaceSlice deprecated

func AnyInterfaceSlice() []interface{}

Deprecated: Use Any[T any]() instead.

func AnyString deprecated

func AnyString() string

Deprecated: Use Any[T any]() instead.

func AnyStringSlice deprecated

func AnyStringSlice() []string

Deprecated: Use Any[T any]() instead.

func AnyUint deprecated

func AnyUint() uint

Deprecated: Use Any[T any]() instead.

func AnyUint16 deprecated

func AnyUint16() uint16

Deprecated: Use Any[T any]() instead.

func AnyUint16Slice deprecated

func AnyUint16Slice() []uint16

Deprecated: Use Any[T any]() instead.

func AnyUint32 deprecated

func AnyUint32() uint32

Deprecated: Use Any[T any]() instead.

func AnyUint32Slice deprecated

func AnyUint32Slice() []uint32

Deprecated: Use Any[T any]() instead.

func AnyUint64 deprecated

func AnyUint64() uint64

Deprecated: Use Any[T any]() instead.

func AnyUint64Slice deprecated

func AnyUint64Slice() []uint64

Deprecated: Use Any[T any]() instead.

func AnyUint8 deprecated

func AnyUint8() uint8

Deprecated: Use Any[T any]() instead.

func AnyUint8Slice deprecated

func AnyUint8Slice() []uint8

Deprecated: Use Any[T any]() instead.

func AnyUintSlice deprecated

func AnyUintSlice() []uint

Deprecated: Use Any[T any]() instead.

func AnyUintptr deprecated

func AnyUintptr() uintptr

Deprecated: Use Any[T any]() instead.

func AnyUintptrSlice deprecated

func AnyUintptrSlice() []uintptr

Deprecated: Use Any[T any]() instead.

func ArgThat

func ArgThat[T any](matcher ArgumentMatcher) T

func BoolSliceThat deprecated

func BoolSliceThat(matcher ArgumentMatcher) []bool

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func BoolThat deprecated

func BoolThat(matcher ArgumentMatcher) bool

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Complex128SliceThat deprecated

func Complex128SliceThat(matcher ArgumentMatcher) []complex128

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Complex128That deprecated

func Complex128That(matcher ArgumentMatcher) complex128

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Complex64SliceThat deprecated

func Complex64SliceThat(matcher ArgumentMatcher) []complex64

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Complex64That deprecated

func Complex64That(matcher ArgumentMatcher) complex64

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func DumpInvocationsFor

func DumpInvocationsFor(mock Mock)

func Eq

func Eq[T any](value T) T

func Float32SliceThat deprecated

func Float32SliceThat(matcher ArgumentMatcher) []float32

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Float32That deprecated

func Float32That(matcher ArgumentMatcher) float32

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Float64SliceThat deprecated

func Float64SliceThat(matcher ArgumentMatcher) []float64

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Float64That deprecated

func Float64That(matcher ArgumentMatcher) float64

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Int16SliceThat deprecated

func Int16SliceThat(matcher ArgumentMatcher) []int16

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Int16That deprecated

func Int16That(matcher ArgumentMatcher) int16

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Int32SliceThat deprecated

func Int32SliceThat(matcher ArgumentMatcher) []int32

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Int32That deprecated

func Int32That(matcher ArgumentMatcher) int32

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Int64SliceThat deprecated

func Int64SliceThat(matcher ArgumentMatcher) []int64

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Int64That deprecated

func Int64That(matcher ArgumentMatcher) int64

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Int8SliceThat deprecated

func Int8SliceThat(matcher ArgumentMatcher) []int8

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Int8That deprecated

func Int8That(matcher ArgumentMatcher) int8

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func IntSliceThat deprecated

func IntSliceThat(matcher ArgumentMatcher) []int

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func IntThat deprecated

func IntThat(matcher ArgumentMatcher) int

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func InterceptMockFailures

func InterceptMockFailures(f func()) []string

InterceptMockFailures runs a given callback and returns an array of failure messages generated by any Pegomock verifications within the callback.

This is accomplished by temporarily replacing the *global* fail handler with a fail handler that simply annotates failures. The original fail handler is reset when InterceptMockFailures returns.

func InterfaceSliceThat deprecated

func InterfaceSliceThat(matcher ArgumentMatcher) []interface{}

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func InterfaceThat deprecated

func InterfaceThat(matcher ArgumentMatcher) interface{}

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func NotEq

func NotEq[T any](value T) T

func RegisterMatcher

func RegisterMatcher(matcher ArgumentMatcher)

func RegisterMockFailHandler

func RegisterMockFailHandler(handler FailHandler)

func RegisterMockTestingT

func RegisterMockTestingT(t *testing.T)

func SDumpInvocationsFor

func SDumpInvocationsFor(mock Mock) string

func StringSliceThat deprecated

func StringSliceThat(matcher ArgumentMatcher) []string

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func StringThat deprecated

func StringThat(matcher ArgumentMatcher) string

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Uint16SliceThat deprecated

func Uint16SliceThat(matcher ArgumentMatcher) []uint16

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Uint16That deprecated

func Uint16That(matcher ArgumentMatcher) uint16

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Uint32SliceThat deprecated

func Uint32SliceThat(matcher ArgumentMatcher) []uint32

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Uint32That deprecated

func Uint32That(matcher ArgumentMatcher) uint32

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Uint64SliceThat deprecated

func Uint64SliceThat(matcher ArgumentMatcher) []uint64

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Uint64That deprecated

func Uint64That(matcher ArgumentMatcher) uint64

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Uint8SliceThat deprecated

func Uint8SliceThat(matcher ArgumentMatcher) []uint8

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func Uint8That deprecated

func Uint8That(matcher ArgumentMatcher) uint8

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func UintSliceThat deprecated

func UintSliceThat(matcher ArgumentMatcher) []uint

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func UintThat deprecated

func UintThat(matcher ArgumentMatcher) uint

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func UintptrSliceThat deprecated

func UintptrSliceThat(matcher ArgumentMatcher) []uintptr

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func UintptrThat deprecated

func UintptrThat(matcher ArgumentMatcher) uintptr

Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.

func When

func When(invocation ...interface{}) *ongoingStubbing

Types

type AnyMatcher

type AnyMatcher struct {
	Type reflect.Type

	sync.Mutex
	// contains filtered or unexported fields
}

func NewAnyMatcher

func NewAnyMatcher(typ reflect.Type) *AnyMatcher

func (*AnyMatcher) FailureMessage

func (matcher *AnyMatcher) FailureMessage() string

func (*AnyMatcher) Matches

func (matcher *AnyMatcher) Matches(param Param) bool

func (*AnyMatcher) String

func (matcher *AnyMatcher) String() string

type ArgumentMatcher

type ArgumentMatcher interface {
	Matches(param Param) bool
	fmt.Stringer
}

ArgumentMatcher can be used to match arguments.

type AtLeastIntMatcher

type AtLeastIntMatcher struct {
	Value int
	// contains filtered or unexported fields
}

func AtLeast

func AtLeast(numDesiredInvocations int) *AtLeastIntMatcher

func (*AtLeastIntMatcher) FailureMessage

func (matcher *AtLeastIntMatcher) FailureMessage() string

func (*AtLeastIntMatcher) Matches

func (matcher *AtLeastIntMatcher) Matches(param Param) bool

func (*AtLeastIntMatcher) String

func (matcher *AtLeastIntMatcher) String() string

type AtMostIntMatcher

type AtMostIntMatcher struct {
	Value int
	// contains filtered or unexported fields
}

func AtMost

func AtMost(numDesiredInvocations int) *AtMostIntMatcher

func (*AtMostIntMatcher) FailureMessage

func (matcher *AtMostIntMatcher) FailureMessage() string

func (*AtMostIntMatcher) Matches

func (matcher *AtMostIntMatcher) Matches(param Param) bool

func (*AtMostIntMatcher) String

func (matcher *AtMostIntMatcher) String() string

type Counter

type Counter struct {
	sync.Mutex
	// contains filtered or unexported fields
}

type EqMatcher

type EqMatcher struct {
	Value Param

	sync.Mutex
	// contains filtered or unexported fields
}

func Never

func Never() *EqMatcher

func Once

func Once() *EqMatcher

func Times

func Times(numDesiredInvocations int) *EqMatcher

func Twice

func Twice() *EqMatcher

func (*EqMatcher) FailureMessage

func (matcher *EqMatcher) FailureMessage() string

func (*EqMatcher) Matches

func (matcher *EqMatcher) Matches(param Param) bool

func (*EqMatcher) String

func (matcher *EqMatcher) String() string

type FailHandler

type FailHandler func(message string, callerSkip ...int)
var GlobalFailHandler FailHandler

func BuildTestingTFailHandler

func BuildTestingTFailHandler(t testingT) FailHandler

type GenericMock

type GenericMock struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func GetGenericMockFrom

func GetGenericMockFrom(mock Mock) *GenericMock

func (*GenericMock) GetInvocationParams

func (genericMock *GenericMock) GetInvocationParams(methodInvocations []MethodInvocation) [][]Param

TODO this doesn't need to be a method, can be a free function

func (*GenericMock) Invoke

func (genericMock *GenericMock) Invoke(methodName string, params []Param, returnTypes []reflect.Type) ReturnValues

func (*GenericMock) Verify

func (genericMock *GenericMock) Verify(
	inOrderContext *InOrderContext,
	invocationCountMatcher InvocationCountMatcher,
	methodName string,
	params []Param,
	options ...interface{},
) []MethodInvocation

type InOrderContext

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

type InvocationCountMatcher

type InvocationCountMatcher interface {
	Matches(param Param) bool
	FailureMessage() string
}

InvocationCountMatcher can be used to match invocation counts. It is guaranteed that FailureMessage will always be called after Matches so an implementation can save state.

type Matcher

type Matcher interface {
	Matches(param Param) bool
	FailureMessage() string
	fmt.Stringer
}

Matcher can be used to match arguments as well as invocation counts. Note that support for overlapping embedded interfaces was added in Go 1.14, which is why ArgumentMatcher and InvocationCountMatcher are not embedded here.

type Matchers

type Matchers []ArgumentMatcher

func (Matchers) Matches

func (matchers Matchers) Matches(params []Param) bool

type MethodInvocation

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

type Mock

type Mock interface {
	SetFailHandler(FailHandler)
	FailHandler() FailHandler
}

type NotEqMatcher

type NotEqMatcher struct {
	Value Param
}

func (*NotEqMatcher) FailureMessage

func (matcher *NotEqMatcher) FailureMessage() string

func (*NotEqMatcher) Matches

func (matcher *NotEqMatcher) Matches(param Param) bool

func (*NotEqMatcher) String

func (matcher *NotEqMatcher) String() string

type Option

type Option interface{ Apply(Mock) }

func WithFailHandler

func WithFailHandler(fail FailHandler) Option

func WithT

func WithT(t testingT) Option

type OptionFunc

type OptionFunc func(mock Mock)

func (OptionFunc) Apply

func (f OptionFunc) Apply(mock Mock)

type Param

type Param interface{}

type ReturnValue

type ReturnValue interface{}

type ReturnValues

type ReturnValues []ReturnValue

type Stubbing

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

func (*Stubbing) Invoke

func (stubbing *Stubbing) Invoke(params []Param) ReturnValues

type Stubbings

type Stubbings []*Stubbing

Directories

Path Synopsis
internal
Package mockgen generates mock implementations of Go interfaces.
Package mockgen generates mock implementations of Go interfaces.
Package model contains the data model necessary for generating mock implementations.
Package model contains the data model necessary for generating mock implementations.
modelgen

Jump to

Keyboard shortcuts

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