mockery - A mock code autogenerator for Golang

mockery

Linux Build Status go.dev reference GitHub go.mod Go version GitHub release (latest SemVer) Go Report Card codecov

mockery provides the ability to easily generate mocks for golang interfaces using the stretchr/testify/mock package. It removes the boilerplate coding required to use mocks.

Table of Contents

Installation

Github Release

Visit the releases page to download one of the pre-built binaries for your platform.

Docker

Use the Docker image

docker pull vektra/mockery

Homebrew

Install through brew

brew install mockery
brew upgrade mockery

go get

Alternatively, you can use the go get method:

go get github.com/vektra/mockery/v2/.../

Note that version strings will not be displayed properly using this method.

Examples

Simplest case

Given this is in string.go

package test

type Stringer interface {
	String() string
}

Run: mockery --name=Stringer and the following will be output to mocks/Stringer.go:

package mocks

import "github.com/stretchr/testify/mock"

type Stringer struct {
	mock.Mock
}

func (m *Stringer) String() string {
	ret := m.Called()

	var r0 string
	if rf, ok := ret.Get(0).(func() string); ok {
		r0 = rf()
	} else {
		r0 = ret.Get(0).(string)
	}

	return r0
}

Function type case

Given this is in send.go

package test

type SendFunc func(data string) (int, error)

Run: mockery --name=SendFunc and the following will be output to mocks/SendFunc.go:

package mocks

import "github.com/stretchr/testify/mock"

type SendFunc struct {
	mock.Mock
}

func (_m *SendFunc) Execute(data string) (int, error) {
	ret := _m.Called(data)

	var r0 int
	if rf, ok := ret.Get(0).(func(string) int); ok {
		r0 = rf(data)
	} else {
		r0 = ret.Get(0).(int)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string) error); ok {
		r1 = rf(data)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

Next level case

See github.com/jaytaylor/mockery-example for the fully runnable version of the outline below.

package main

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/jaytaylor/mockery-example/mocks"
	"github.com/stretchr/testify/mock"
)

func main() {
	mockS3 := &mocks.S3API{}

	mockResultFn := func(input *s3.ListObjectsInput) *s3.ListObjectsOutput {
		output := &s3.ListObjectsOutput{}
		output.SetCommonPrefixes([]*s3.CommonPrefix{
			&s3.CommonPrefix{
				Prefix: aws.String("2017-01-01"),
			},
		})
		return output
	}

	// NB: .Return(...) must return the same signature as the method being mocked.
	//     In this case it's (*s3.ListObjectsOutput, error).
	mockS3.On("ListObjects", mock.MatchedBy(func(input *s3.ListObjectsInput) bool {
		return input.Delimiter != nil && *input.Delimiter == "/" && input.Prefix == nil
	})).Return(mockResultFn, nil)

	listingInput := &s3.ListObjectsInput{
		Bucket:    aws.String("foo"),
		Delimiter: aws.String("/"),
	}
	listingOutput, err := mockS3.ListObjects(listingInput)
	if err != nil {
		panic(err)
	}

	for _, x := range listingOutput.CommonPrefixes {
		fmt.Printf("common prefix: %+v\n", *x)
	}
}

Return Value Provider Functions

If your tests need access to the arguments to calculate the return values, set the return value to a function that takes the method's arguments as its own arguments and returns the return value. For example, given this interface:

package test

type Proxy interface {
  passthrough(ctx context.Context, s string) string
}

The argument can be passed through as the return value:

import . "github.com/stretchr/testify/mock"

Mock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).Return(func(ctx context.Context, s string) string {
    return s
})

Requirements

Return must be passed the same argument count and types as expected by the interface. Then, for each of the return values of the mocked function, Return needs a function which takes the same arguments as the mocked function, and returns one of the return values. For example, if the return argument signature of passthrough in the above example was instead (string, error) in the interface, Return would also need a second function argument to define the error value:

type Proxy interface {
  passthrough(ctx context.Context, s string) (string, error)
}
Mock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).Return(
	func(ctx context.Context, s string) string {
		return s
	},
	func(ctx context.Context, s string) error {
		return nil
	})

Note that the following is incorrect (you can't return all the return values with one function):

Mock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).Return(
	func(ctx context.Context, s string) (string, error) {
		return s, nil
	})

If any return argument is missing, github.com/stretchr/testify/mock.Arguments.Get will emit a panic.

For example, panic: assert: arguments: Cannot call Get(0) because there are 0 argument(s). [recovered] indicates that Return was not provided any arguments but (at least one) was expected based on the interface. Get(1) would indicate that the Return call is missing a second argument, and so on.

Notes

This approach should be used judiciously, as return values should generally not depend on arguments in mocks; however, this approach can be helpful for situations like passthroughs or other test-only calculations.

Extended Flag Descriptions

The following descriptions provide additional elaboration on a few common parameters.

flag name description
--name The --name option takes either the name or matching regular expression of interface to generate mock(s) for.
--all It's common for a big package to have a lot of interfaces, so mockery provides --all. This option will tell mockery to scan all files under the directory named by --dir ("." by default) and generates mocks for any interfaces it finds. This option implies --recursive=true.
--recursive Use the --recursive option to search subdirectories for the interface(s). This option is only compatible with --name. The --all option implies --recursive=true.
--output mockery always generates files with the package mocks to keep things clean and simple. You can control which mocks directory is used by using --output, which defaults to ./mocks.
--inpackage and --keeptree For some complex repositories, there could be multiple interfaces with the same name but in different packages. In that case, --inpackage allows generating the mocked interfaces directly in the package that it mocks. In the case you don't want to generate the mocks into the package but want to keep a similar structure, use the option --keeptree.
--filename Use the --filename and --structname to override the default generated file and struct name. These options are only compatible with non-regular expressions in --name, where only one mock is generated.
--case mockery generates files using the casing of the original interface name. This can be modified by specifying --case underscore to format the generated file name using underscore casing.
--print Use mockery --print to have the resulting code printed out instead of written to disk.
--exported Use mockery --exported to generate public mocks for private interfaces.

Mocking interfaces in main

When your interfaces are in the main package you should supply the --inpackage flag. This will generate mocks in the same package as the target code avoiding import issues.

Configuration

mockery uses spf13/viper under the hood for its configuration parsing. It is bound to three different configuration sources, in order of decreasing precedence:

  1. Command line
  2. Environment variables
  3. Configuration file

Example

$ export MOCKERY_STRUCTNAME=config_from_env
$ echo $MOCKERY_STRUCTNAME
config_from_env
$ grep structname .mockery.yaml
structname: config_from_file
$ ./mockery showconfig --structname config_from_cli | grep structname
Using config file: /home/ltclipp/git/vektra/mockery/.mockery.yaml
structname: config_from_cli
$ ./mockery showconfig  | grep structname
Using config file: /home/ltclipp/git/vektra/mockery/.mockery.yaml
structname: config_from_env
$ unset MOCKERY_STRUCTNAME
$ ./mockery showconfig  | grep structname
Using config file: /home/ltclipp/git/vektra/mockery/.mockery.yaml
structname: config_from_file

By default it searches the current working directory for a file named .mockery.[extension] where [extension] is any of the recognized extensions.

Semantic Versioning

The versioning in this project applies only to the behavior of the mockery binary itself. This project explicitly does not promise a stable internal API, but rather a stable executable. The versioning applies to the following:

  1. CLI arguments.
  2. Parsing of Golang code. New features in the Golang language will be supported in a backwards-compatible manner, except during major version bumps.
  3. Behavior of mock objects. Mock objects can be considered to be part of the public API.
  4. Behavior of mockery given a set of arguments.

What the version does not track:

  1. The interfaces, objects, methods etc. in the vektra/mockery package.
  2. Compatibility of go get-ing mockery with new or old versions of Golang.

Development Efforts

v2 is in a soft change freeze due to the complexity of the software and the fact that functionality addition generally requires messing with logic that has been thoroughly tested, but is sensitive to change.

v1

v1 is the original version of the software, and is no longer supported.

v2

mockery is currently in v2, which iterates on v1 and includes mostly cosmetic and configuration improvements.

v3

v3 will include a ground-up overhaul of the entire codebase and will completely change how mockery works internally and externally. The highlights of the project are:

  • Moving towards a package-based model instead of a file-based model. mockery currently iterates over every file in a project and calls package.Load on each one, which is time consuming. Moving towards a model where the entire package is loaded at once will dramtically reduce runtime, and will simplify logic. Additionally, supporting only a single mode of operation (package mode) will greatly increase the intuitiveness of the software.
  • Configuration-driven generation. v3 will be entirely driven by configuration, meaning:
    • You specify the packages you want mocked, instead of relying on it auto-discovering your package. Auto-discovery in theory sounds great, but in practice it leads to a great amount of complexity for very little benefit.
    • Package- or interface-specific overrides can be given that change mock generation settings on a granular level. This will allow your mocks to be generated in a heterogenous manner, and will be made explicit by yaml configuration.
  • Proper error reporting. Errors across the board will be done in accordance with modern Golang practices
  • Variables in generated mocks will be given meaningful names.

Stargazers

Stargazers over time

Owner
Vektra
Infrastructure Everywhere
Vektra
Comments
  • Add support for generating mocks for generic interfaces

    Add support for generating mocks for generic interfaces

    Description

    This adds support for generating mocks for generic interfaces. It does bump the go version to 1.18 so not sure how you want to handle this.

    • Fixes #451

    Type of change

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [x] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [x] This change requires a documentation update

    Version of Golang used when building/testing:

    • [ ] 1.11
    • [ ] 1.12
    • [ ] 1.13
    • [ ] 1.14
    • [ ] 1.15
    • [ ] 1.16
    • [ ] 1.17
    • [x] 1.18

    How Has This Been Tested?

    I've added unit tests for different types of generic interfaces, happy to add any others you think are worthwhile.

    Checklist

    • [x] My code follows the style guidelines of this project
    • [x] I have performed a self-review of my code
    • [x] I have commented my code, particularly in hard-to-understand areas
    • [ ] I have made corresponding changes to the documentation
    • [x] My changes generate no new warnings
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] New and existing unit tests pass locally with my changes
  • symlinked /mockery to /usr/local/bin

    symlinked /mockery to /usr/local/bin

    A lot of the code I maintain depends on using go generate to create our mockery code with this pattern: //go:generate mockery -name=MockedInterface

    • Adding the symlink to /go/bin ensures that go generate will work regardless whether mockery is called from a local installation or the docker container.
  • import cycle

    import cycle

    $ pwd
    /Users/tejas/dev/src/github.com/NetSys/quilt/cluster/provider
    $ mockery -name=EC2Client
    Generating mock for: EC2Client
    $ tree
    .
    ├── amazon_test.go
    ├── awsSpot.go
    ├── cloud_config.go
    ├── constraint.go
    ├── gce.go
    ├── mocks
    │   └── EC2Client.go
    ├── provider.go
    ├── provider_test.go
    ├── vagrant.go
    └── vagrant_api.go
    
    1 directory, 10 files
    
    

    mocks/EC2Client.go is the generated file. That file is shown here. The last line var _ provider.EC2Client = (*EC2Client)(nil) causes an import cycle

    $ go test ./cluster/provider
    # github.com/NetSys/quilt/cluster/provider
    import cycle not allowed in test
    package github.com/NetSys/quilt/cluster/provider (test)
            imports github.com/NetSys/quilt/cluster/provider/mocks
            imports github.com/NetSys/quilt/cluster/provider
    
    FAIL    github.com/NetSys/quilt/cluster/provider [setup failed]
    

    I assume this line is to test that the interface is satisfied by the mock. That seems like a good idea, but do you have any suggestions on how to avoid to import cycle? Should the default be changed from generating in ./mocks?

  • Add mock generation with expecter

    Add mock generation with expecter

    Note: This PR is still prototypical, code is a bit messy. However, the general functionality should be stable and I'm mostly requesting for comments to see if that is something anyone would be interested on the main branch (currently using it in other projects).

    All comments are more than welcomed.

    Motivation for feature

    Setting up mocks has always been a lot of guesswork or going back and forth between the tests and the interface's definition. The mockery framework already extracts all necessary information for this, it seems a logical next step to have type explicit mock construction.

    Goal

    Adds flag --with-expecter which generates boilerplate code over all of relevant mocks's functions that are missing type safety with the current way of defining mocks. Generates the usual mock boilerplate, plus an Expecter structure for setting up calls. The naming is inspired by GoMock.

    Works with variadic methods, but not if the flag --unroll-variadic=false is set (not using it in my projects, didn't take the time to look at feasibility with it really...)

    Example

    Given an interface such as

    type Requester interface {
    	Get(path string) (string, error)
    }
    

    Generates the following as well as the usual Get mock.Called wrapper

    // Requester is an autogenerated mock type for the Requester type
    type Requester struct {
            mock.Mock
    }
    
    type Requester_Expecter struct {
    	mock *mock.Mock
    }
    
    func (_m *Requester) EXPECT() *Requester_Expecter {
    	return &Requester_Expecter{mock: &_m.Mock}
    }
    
    // Requester_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
    type Requester_Get_Call struct {
    	*mock.Call
    }
    
    // Get is a helper method to define mock.On call
    //  - path string
    func (_e *Requester_Expecter) Get(path interface{}) *Requester_Get_Call {
    	return &Requester_Get_Call{Call: _e.mock.On("Get", path)}
    }
    
    func (_c *Requester_Get_Call) Run(run func(path string)) *Requester_Get_Call {
    	_c.Call.Run(func(args mock.Arguments) {
    		run(args[0].(string))
    	})
    	return _c
    }
    
    func (_c *Requester_Get_Call) Return(_a0 string, _a1 error) *Requester_Get_Call {
    	_c.Call.Return(_a0, _a1)
    	return _c
    }
    

    So that one can use it like so

    requesterMock := Requester{}
    requesterMock.EXPECT().Get("some path").Return("result", nil)
    requesterMock.EXPECT().
    	Get(mock.Anything).
    	Run(func(path string) { fmt.Println(path, "was called") }).
    	// Can still use return functions by getting the embedded mock.Call
    	Call.Return(func(path string) string { return "result for " + path }, nil)
    

    Pros:

    • Backward compatible with current mockery
    • Still keeps advantages of mock.Anything and mock.MatchedBy(func), but prints the concrete type in docstring of the Expecter method.
    • IntelliSense, autocomplete, call documentation... when setting up mocked calls.
    • Compile time error on erroneous arguments.
    • Easy refactoring when interface changes.

    Cons:

    • Does not work if the mocked interface already has a method named EXPECT (should be easy to fix, unnecessary for RFC)
    • About 2.5x more boilerplate code.
    • Uses golang's templating system which is non standard for this project.
    • Not all mock.Call methods are defined, if one wants to use Run or Return, it needs to be before the others, which might be a bit confusing. For example EXPECT().Get("").Return(...).Once().Run(...) wouldn't compile while EXPECT().Get("").Return(...).Run(...).Once() would. This could be fixed by redefining all underlying methods to return the concrete Call struct, at the cost of more boilerplate of course.

    Further amelioration

    The *_Expecter and *_Call structs could be unexported and still usable as far as I can see.

    Addition of a RunAndReturn function that takes a function with exact same signature as mocked method and defines the Return function with the result of the Run function. I ran into a potential race issue with this though and didn't go further. Might look into it more if there is a need.

    Make it work with --unroll-variadic maybe, for now it crashes. To be honest, I think that might be useless or even counter-productive though...

  • Fix go 1.14: Update to latest golang.org/x/tools

    Fix go 1.14: Update to latest golang.org/x/tools

    This fixes a compatibility issue with go1.14 by upgrading to the latest x/tools package.

    2020/03/23 16:19:15 internal error: nil Pkg importing "github.com/vektra/mockery/mockery/fixtures/http" from "github.com/vektra/mockery/mockery/fixtures"
    FAIL	github.com/vektra/mockery/mockery	0.309s
    
  • Unable to find Stringer in any go files under this path

    Unable to find Stringer in any go files under this path

    Can you please help, what I might be missing?

    Screen Shot 2020-10-28 at 12 15 48 AM
    $go version
    warning: GOPATH set to GOROOT (/Users/abc/go) has no effect
    go version go1.14.6 darwin/amd64
    
  • mock generation fails if another package exists in the same directory as the package that contains the interface

    mock generation fails if another package exists in the same directory as the package that contains the interface

    For example, if I have a directory structure similar to:

    /client/client.go
    /client/client_test.go
    

    Where client.go is in the client package and client_test.go is in the client_test package, I see the following error when generating a mock:

    Error parsing file:  client_test.go:3:1: package client_test; expected client
    

    The current workaround is to temporarily delete the *_test package before running mockery to generate the mock.

  • Add constructor for mocks

    Add constructor for mocks

    These changes will simplify the tests by not being required to assert mocks expectations every time. This will also eliminate situations where your tests are not failing even though they should, only to find out that you forget the defer statement.

    Example Before:

    factory := &mocks.Factory{}
    defer factory.AssertExpectations()
    
    something := &mocks.Something{}
    defer something.AssertExpectations()
    
    something.On("GetTime").Return("tooLate")
    
    factory.On("Create").Return(something)
    
    testThings(factory)
    

    Now:

    factory := mocks.NewFactory()
    something := mocks.NewSomething()
    
    something.On("GetTime").Return("tooLate")
    
    factory.On("Create").Return(something)
    
    testThings(factory)
    

    edit: this already got merged: These changes are based on a branch where I did some refactoring, you can see it here https://github.com/vektra/mockery/pull/399. If you don't intend to merge the refactoring PR, I can rebase this branch onto the master.

  • proposal: add spinner to cli output while loading files

    proposal: add spinner to cli output while loading files

    If there are many files to parse this function can take quite a while to return. Suggestion is to modify code to print spinner to cli so users don't get impatient

    https://github.com/vektra/mockery/blob/master/mockery/parse.go#L101-L131

    There are packages that provide such functionality. Such as https://github.com/briandowns/spinner

    But unsure of the policy on using external packages

  • Invalid mock generated with the same package names

    Invalid mock generated with the same package names

    Using either 1.1.2 or 2.0.0-alpha.13 release builds of mockery we have the following issue

    cloudformation/interface.go

    package cloudformation
    
    import "github.com/aws/aws-sdk-go/service/cloudformation"
    
    type invalid interface {
    	String(*cloudformation.CreateStackInput) string
    }
    

    main.go

    package main
    
    func main() {}
    

    generates a mock like like the following when using mockery -all -testonly -inpkg

    // Code generated by mockery v1.1.2. DO NOT EDIT.
    
    package cloudformation
    
    import mock "github.com/stretchr/testify/mock"
    
    // mockInvalid is an autogenerated mock type for the invalid type
    type mockInvalid struct {
    	mock.Mock
    }
    
    // String provides a mock function with given fields: _a0
    func (_m *mockInvalid) String(_a0 *cloudformation.CreateStackInput) string {
    	ret := _m.Called(_a0)
    
    	var r0 string
    	if rf, ok := ret.Get(0).(func(*cloudformation.CreateStackInput) string); ok {
    		r0 = rf(_a0)
    	} else {
    		r0 = ret.Get(0).(string)
    	}
    
    	return r0
    }
    

    You can see the import for cloudformation is missing and in turn the go reports undefined: cloudformation in the mock file.

    It seems like when the cloudformation directory is at the root the issue cannot be re-created. When mockery is built from source either via go get or cloning and go install this issue seems to go away and the import is generated properly. As installing is not supported using go get anymore our mocks are no longer generating properly.

    package cloudformation
    
    import (
    	"github.com/aws/aws-sdk-go/service/cloudformation"
    	mock "github.com/stretchr/testify/mock"
    )
    
  • Add configuration for goreleaser

    Add configuration for goreleaser

    This adds basic configuration for goreleaser. On a tagged release it will build for linux, osx and windows, and add to the GitHub release page, including the artifacts, changelog and checksum file. To test locally you can run goreleaser --snapshot --skip-publish --rm-dist

    I've also change the SemVer to be auto generated at build time via ldflags; This may cause slight confusion for people installing via go get as it will display 0.0.0-dev, but allows easier version management via CI releases (with goreleaser); In the future we should favour CI builds over using go get.

    This is a prerequisite to having other distributions such as docker (#180) and homebrew (recommended)

    I've amended CI (travis) to run the tests and do a deploy when there is a valid release tagged.

  • Improve generation performance by calling packages.Load only once

    Improve generation performance by calling packages.Load only once

    I've discovered that we can likely get a huge performance benefit by calling packages.Load only once. Currently, it is called once per file, which means that the entire dep tree is being loaded multiple times, thus resulting in O(n^2) performance. We should instead gather the list of files to load, then make one call to packages.Load. This should improve performance.

    https://github.com/vektra/mockery/blob/master/pkg/parse.go#L76

    https://github.com/vektra/mockery/blob/master/pkg/parse.go#L100

  • Is there a way to mock an anonymous function and call another mock inside it?

    Is there a way to mock an anonymous function and call another mock inside it?

    I am trying to mock a Backoff strategy with the following interface:

    type Backoff interface {
    	Retry(func() error) error
    }
    

    and a production code

    err = s.serviceX.Retry(func() error {
            data, err = s.serviceY.SomeFunction(queryParams)
    	if err != nil {
    	        return err
    	}
    	return nil
    })
    

    and them in tests, trying...:

    serviceX := storeMocks.ServiceXXX(t)
    serviceX.On("Retry", mock.AnythingOfType("func() error")).Return(...)
    
    serviceY := storeMocks.ServiceXXX(t)
    serviceY.On("SomeFunction", mock.AnythingOfType("string")).Return(...)
    
    

    I'm unsure what the following steps are to call these two functions. The first one is always called. But I'd like to call SomeFunction too.

    Currently, I'm not mocking the first function yet, only using a dumb implementation e.g.:

    func (c dumbStrategy) Retry(f func() error) error {
    	return f()
    }
    
    func NewDumbStrategy(err error) Backoff {
    	return &dumbStrategy{}
    }
    
  • Difference in whitespace with the same version.

    Difference in whitespace with the same version.

    Description

    I run into very strange issue. When generating expecter, list of parameters in doc comment has THREE spaces instead of TWO in front of each dash.

     // GetID is a helper method to define mock.On call
    -//  - _a0 context.Context
    -//  - _a1 string
    +//   - _a0 context.Context
    +//   - _a1 string
    

    I've tried:

    • Different versions of mockery (homebrew and go install)
    • Different versions of go
    • Cleaning golang cache (-cache, -modcache, -testcache)
    • Removing whole GOPATH
    • Modifying source code and recompiling mockery with slightly different template

    The last one lead to absolutely ridiculous discoveries where I pretty much can have ONE space or THREE, but never TWO.

    Workaround for me right now is to replace // - with // - after generating mocks.

    My wild guess is that dash - in template messes up with it as it's also used to trim white spaces.

    I get THREE spaces when I have this original template:

    // {{.MethodName}} is a helper method to define mock.On call
    {{- range .Params.Params}}
    //  - {{.}}
    {{- end}}
    

    I get ONE space if I remove one:

    // {{.MethodName}} is a helper method to define mock.On call
    {{- range .Params.Params}}
    // - {{.}}
    {{- end}}
    

    I'm at the stage where I'm willing to open a pull request to remove that one unnecessary space - would you accept it? I know the issue seems to be on my side but I can't track it down and that one space looks totally unnecessary ;d

    Mockery Version

    % mockery --version
    07 Nov 22 19:40 CET INF Starting mockery dry-run=false version=v2.14.0
    v2.14.0
    

    Golang Version

    kdz@dz ~ % go version
    go version go1.19.3 darwin/arm64
    

    Installation Method

    • [ ] Binary Distribution
    • [ ] Docker
    • [x] brew
    • [x] go install
    • [ ] Other: [specify]

    Steps to Reproduce

    Just run mockery --all --exported --with-expecter on my laptop :)

    Expected Behavior

    I should have TWO white spaces.

    Actual Behavior

    I have THREE white spaces.

     // GetID is a helper method to define mock.On call
    -//  - _a0 context.Context
    -//  - _a1 string
    +//   - _a0 context.Context
    +//   - _a1 string
    
  • mockery Error parsing file  could not import golang.org/x/sync/semaphore (invalid package name: \

    mockery Error parsing file could not import golang.org/x/sync/semaphore (invalid package name: \"\")

    golang version go1.17.6 linux/amd64 mockery dry-run=false version=v2.9.4

    go.mod require golang.org/x/sync v0.1.0

    go mod download

    go.sum 
          golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
          golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
          golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
    

    log.go import ( "golang.org/x/sync/semaphore" )

    mockery --all --inpackage --keeptree --output /root/baisheng/

    27 Oct 22 07:32 UTC INF Starting mockery dry-run=false version=v2.9.4 27 Oct 22 07:32 UTC INF Walking dry-run=false version=v2.9.4 27 Oct 22 07:33 UTC ERR Error parsing file error="/root/baisheng/ git/ log.go:11:2: could not import golang.org/x/sync/semaphore (invalid package name: \" \")" dry-run=false version=v2.9.4

  • Bug: Cannot return nil for generic type T, when T is an interface

    Bug: Cannot return nil for generic type T, when T is an interface

    Description

    For the interfaces

    type Builder[T any] interface {
    	Build() (T, error)
    }
    
    type Thing interface {
    	DoStuff()
    }
    

    I'd like to mock Builder behavior as

    thingBuilder := new(mocks.Builder[Thing])
    thingBuilder.On("Build").Return(nil, errors.New("some error"))
    

    But I get an error like:

    panic: interface conversion: interface is nil, not Thing
    

    Shouldn't mockery know that Thing is an interface and so Builder[Thing].Build() should be able to return (nil, error)?

    Mockery Version

    $ mockery --version
    19 Oct 22 17:49 MDT INF Starting mockery dry-run=false version=v2.14.0
    v2.14.0
    

    Golang Version

    $ go version
    go version go1.19 linux/amd64
    

    Installation Method

    • [ ] Binary Distribution
    • [ ] Docker
    • [ ] brew
    • [x] go install
    • [ ] Other: [specify]

    Expected Behavior

    Can mock generic return types as nil when they are in fact interfaces.

    Actual Behavior

    Tests panic

Vault mock - Mock of Hashicorp Vault used for unit testing

vault_mock Mock of Hashicorp Vault used for unit testing Notice This is a person

Jan 19, 2022
Mock-the-fck - Mock exercise for human

Mock the fck Originally, Mockery-example Example case for mockery issue #128 fil

Jan 21, 2022
Sql mock driver for golang to test database interactions

Sql driver mock for Golang sqlmock is a mock library implementing sql/driver. Which has one and only purpose - to simulate any sql driver behavior in

Dec 31, 2022
HTTP mock for Golang: record and replay HTTP/HTTPS interactions for offline testing

govcr A Word Of Warning I'm in the process of partly rewriting govcr to offer better support for cassette mutations. This is necessary because when I

Dec 28, 2022
Just Dance Unlimited mock-up server written on Golang and uses a popular Gin framework for Go.

BDCS Just Dance Unlimited mock-up server written on Golang and uses a popular Gin framework for Go. Features Security Authorization works using UbiSer

Nov 10, 2021
A simple mock server configurable via JSON, built using GoLang.
A simple mock server configurable via JSON, built using GoLang.

GoMock Server A simple mock server configurable via JSON, built using GoLang. How To A file name endpoint.json must be placed in the context root, wit

Nov 19, 2022
Grpcmock - Mock grpc server with golang

grpcmock Mock gRPC server. Inspired by Prism. Add example responses to your prot

May 8, 2022
Test your code without writing mocks with ephemeral Docker containers 📦 Setup popular services with just a couple lines of code ⏱️ No bash, no yaml, only code 💻

Gnomock – tests without mocks ??️ Spin up entire dependency stack ?? Setup initial dependency state – easily! ?? Test against actual, close to product

Dec 29, 2022
Powerful mock generation tool for Go programming language

Summary Minimock generates mocks out of Go interface declarations. The main features of minimock are: It generates statically typed mocks and helpers.

Dec 17, 2022
Mock object for Go http.ResponseWriter

mockhttp -- Go package for unit testing HTTP serving Unit testing HTTP services written in Go means you need to call their ServeHTTP receiver. For thi

Sep 27, 2022
ESME is a go library that allows you to mock a RESTful service by defining the configuration in json format

ESME is a go library that allows you to mock a RESTful service by defining the configuration in json format. This service can then simply be consumed by any client to get the expected response.

Mar 2, 2021
Create your own mock server with just a JSON file!

Gmocker Run a blazing fast mock server in just seconds! ?? All you need is to make a json file that contains path and response mapping. See an example

Dec 21, 2022
Create your own blazing fast mock server with just a JSON file!

Gmocker Run a blazing fast mock server in just seconds! ?? All you need is to make a json file that contains path and response mapping. See an example

Dec 21, 2022
Dec 8, 2022
Completely type-safe compile-time mock generator for Go

Mockc Mockc is a completely type-safe compile-time mock generator for Go. You can use it just by writing the mock generators with mockc.Implement() or

Aug 25, 2022
Merge Mock - testing tool for the Ethereum Merge

MergeMock Experimental debug tooling, mocking the execution engine and consensus node for testing. work in progress Quick Start To get started, build

Oct 21, 2022
A basic lightweight HTTP client for Go with included mock features.

A basic lightweight HTTP client for Go with included mock features. Features Support almost all http method like G

May 2, 2022
📡 mock is a simple, cross-platform, cli app to simulate HTTP-based APIs.
 📡 mock is a simple, cross-platform, cli app to simulate HTTP-based APIs.

mock ?? mock is a simple, cross-platform, cli app to simulate HTTP-based APIs. About mock Mock allows you to spin up a local http server based of a .m

May 6, 2022
A mock of Go's net package for unit/integration testing

netmock: Simulate Go network connections netmock is a Go package for simulating net connections, including delays and disconnects. This is work in pro

Oct 27, 2021