mockery - A mock code autogenerator for Golang

Overview

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

Issues
  • 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
    opened by cruickshankpg 27
  • 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.
    opened by mkatychev 27
  • 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?

    opened by tejasmanohar 17
  • 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...

    opened by Gevrai 15
  • 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
    
    opened by Willyham 15
  • 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.

    opened by tescherm 13
  • 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.

    opened by grongor 11
  • 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

    opened by tamccall 11
  • 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"
    )
    
    opened by RossHammer 10
  • 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.

    enhancement Tentative Approval 
    opened by rogchap 10
  • Unable to get writer when used with -inpkg option

    Unable to get writer when used with -inpkg option

    Hi I encounter problem when using mockery with -inpkg option how I use it: mockery -name IBookingService -case=underscore -inpkg error msg: Unable to get writer for IBookingService: open gitlab.myteksi.net/gophers/go/food/external/mock_i_booking_service.go: no such file or directory

    I suspect this is due to the recent change ( https://github.com/vektra/mockery/commit/2be70d1c16b905d1ebbb3f1da219b11de416a0e6#diff-9fccd60b1234c112849b2bdd764adae3R159 ): pkg.Path used to be the path of the file containing the interface, but now entry.pkg.Types points to the director of the file of the interface. I might be wrong

    opened by wulifu2hao 10
  • fix: add support for with-expecter when using generics

    fix: add support for with-expecter when using generics

    Description

    When generating generic mocks with with-expecter: true, the generated code is invalid and does not build. This means codebase which have generics cannot use with-expecter: true (which is a shame!).

    This PR fixes this issue without any breaking changes.

    One consideration: I had to add 2 extra calls to getInstantiatedTypeString and getTypeConstraintString, not sure if this could have some impact on performance and should be performed once for the whole file or if 3 times per file is ok.

    Type of change

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [ ] 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?

    Added an extra unit test in generator_test.go, tested on my company codebase which includes 2 different generic types and loads of other interfaces.

    Checklist

    • [x] My code follows the style guidelines of this project
    • [x] I have performed a self-review of my code
    • ~[ ] I have commented my code, particularly in hard-to-understand areas~ none required (?)
    • ~[ ] I have made corresponding changes to the documentation~ none required
    • [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
    opened by LouisBrunner 2
  • Packages with `.` in them are incorrectly imported in mocks

    Packages with `.` in them are incorrectly imported in mocks

    Description

    When importing the library github.com/nats-io/nats.go and generating mock, the resulting import in the generated mock is missing the nats.go part (github.com/nats-io/).

    Mockery Version

    12.13.1

    Golang Version

    go1.18 darwin/arm64

    Installation Method

    • [ ] Binary Distribution
    • [ ] Docker
    • [x] brew
    • [ ] go install
    • [x] Other: Another colleague compiled from source and gets the same result

    Steps to Reproduce

    1. Add the following import to a file: nats "github.com/nats-io/nats.go"
    2. Use the package in an interface
    3. Generate mocks for said interface
    4. Observe that the generated mock import is nats "github.com/nats-io/"

    Expected Behavior

    I expect to the generated mock to import nats "github.com/nats-io/nats.go"

    Actual Behavior

    The generated mock imports nats "github.com/nats-io/"

    opened by taylow 1
  • g.iface.NamedType.TypeParams undefined (type *types.Named has no field or method TypeParams)

    g.iface.NamedType.TypeParams undefined (type *types.Named has no field or method TypeParams)

    Description

    Code:

    //go:generate go run -mod=mod github.com/vektra/mockery/v2 --inpackage --case underscore --name=Client
    type Client interface {...}
    

    Logs:

    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:75:33: g.iface.NamedType.TypeParams undefined (type *types.Named has no field or method TypeParams)
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:82:31: g.iface.NamedType.TypeArgs undefined (type *types.Named has no field or method TypeArgs)
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:271:25: g.iface.NamedType.TypeParams undefined (type *types.Named has no field or method TypeParams)
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:287:25: g.iface.NamedType.TypeParams undefined (type *types.Named has no field or method TypeParams)
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:403:7: t.TypeArgs undefined (type *types.Named has no field or method TypeArgs)
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:406:30: t.TypeArgs undefined (type *types.Named has no field or method TypeArgs)
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:407:[20](https://github.com/angell-bike/angell-services/runs/6877143488?check_suite_focus=true#step:6:21): t.TypeArgs undefined (type *types.Named has no field or method TypeArgs)
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:408:12: t.TypeArgs undefined (type *types.Named has no field or method TypeArgs)
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:412:8: undefined: types.TypeParam
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:491:8: undefined: types.Union
    Error: /home/runner/go/pkg/mod/github.com/vektra/mockery/[email protected]/pkg/generator.go:491:8: too many errors
    

    Version

    v2.13.0

    Steps to Reproduce

    1. go generate
    opened by euskadi31 3
  • Running under go 1.18 throws 'package without types' error

    Running under go 1.18 throws 'package without types' error

    Description

    go generate runs mockery --name .* When I ran this under go 1.17 there are no problems. After upgrading to go 1.18 I get an error: internal error: package "privaterepo/pkgone" without types was imported from "privaterepo/pkgtwo"

    Version

    mockery --version outputs: 07 Jun 22 18:48 MDT INF Starting mockery dry-run=false version=v0.0.0-dev v0.0.0-dev

    I installed mockery_2.13.0-beta.1_Darwin_x86_64.tar.gz

    Steps to Reproduce

    Explained above. Note: I kept go 1.17 on my machine and running go1.17 generate has no problem.

    Expected Behavior

    mocks to be created

    Actual Behavior

    Got an error. See description

    opened by pantsmann 3
  • Add documentation for --outpkg to readme

    Add documentation for --outpkg to readme

    Description

    Added documentation for a parameter flag - I'd expected the --output flag to change both directory and package name, so when I realized it only changed the directory, I went digging in code for this one.

    Type of change

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] 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:

    N/A, this is a documentation-only change.

    How Has This Been Tested?

    N/A, this is a documentation-only change.

    Checklist

    • [x] My code follows the style guidelines of this project
    • [x] I have performed a self-review of my code
    • [ ] I have commented my code, particularly in hard-to-understand areas
    • [x] I have made corresponding changes to the documentation
    • [x] My changes generate no new warnings
    • [ ] 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
    opened by RSid 0
  • Generating a mock for external _test package

    Generating a mock for external _test package

    I would imagine a lot of mocks are generated to be used in _test files, with _test package names. To generate one using mockery is a bit cumbersom. ie this is great mockery --inpackage --name NodeAndOptionsGetter but will generate a mock as the main package, meaning having to import it to *_test tests (not the end of the world I know)

    To get the same mock, with the same MockNodeAndOptionsGetter name, in the same directory, with the same mock_ prefix, but with the _test suffix, and using the _test package, this is what you seemingly have to write:

    mockery --output ./ --name NodeAndOptionsGetter --outpkg handler_test --filename mock_NodeAndOptionsGetter_test.go --structname MockNodeAndOptionsGetter

    That's a lot of boilerplate, when tbh I would have thought the --testonly flag would do it all (which in fact on it's own is a compile error due to it not bing in a _test.go file). Is there a better way to do it that I'm not seeing?

    Version

    v2.10.0

    opened by MichaelMallett 1
Releases(v2.13.1)
Owner
Vektra
Infrastructure Everywhere
Vektra
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

Elliot Rotenstein 0 Jan 19, 2022
Mock-the-fck - Mock exercise for human

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

Mike Cat 0 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

DATA-DOG 4.5k Jun 25, 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

Seb C 105 May 18, 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

Mikhail 0 Nov 10, 2021
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

Miguel Alexandre 0 Jan 9, 2022
Grpcmock - Mock grpc server with golang

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

Eric Butler 3 May 8, 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.

Juno Inc. 455 Jun 15, 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

Tv 21 Mar 22, 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.

Sumit Tokkar 3 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

Ananto 49 Apr 13, 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

Ananto 49 Apr 13, 2022
Vitaly Berg 7 Aug 10, 2021
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

Geon Kim 29 May 23, 2021
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

Diederik Loerakker 33 Jun 17, 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

Andres Mijares 1 May 2, 2022
📡 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

Bruno Schaatsbergen 8 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

Lucas Wolf 1 Oct 27, 2021
Mock API for REST!!!!

Mock API Server Introduction This app allows you to add urls and serve dummy json responses. It contains two handlers, the DummyHandler allows you to

null 2 Jun 20, 2022