Code Monkey home page Code Monkey logo

mockery's Introduction

mockery

Release 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.

Documentation

Documentation is found at out GitHub Pages site.

Development

taskfile.dev is used for build tasks. Initialize all go build tools:

go mod download -x

You can run any of the steps listed in Taskfile.yml:

$ task test
task: [test] go test -v -coverprofile=coverage.txt ./...

Development Efforts

v1

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

v2

mockery is currently in v2, which originally included cosmetic and configuration improvements over v1, but also implements a number of quality-of-life additions.

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 dramatically 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 heterogeneous 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

mockery's People

Contributors

atombender avatar cam72cam avatar colonelpanic8 avatar cszczepaniak avatar dakiva avatar dillonstreator avatar dlwyatt avatar dustinjsilk avatar dwlnetnl avatar emmanuel099 avatar ernesto-jimenez avatar evanphx avatar gaffo avatar georgysavva avatar grongor avatar hikyaru-suzuki avatar hohmannr avatar jokly avatar joshk0 avatar kbolino avatar landontclipp avatar mateusmarquezini avatar mkatychev avatar nmiyake avatar rangelreale avatar rogchap avatar ryanbrainard avatar sirsova avatar tamccall avatar tehbilly avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mockery's Issues

Seemingly wrong Return(func) behavior

Such an interface:

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

generates:

func (_m *Requester) Get(path string) (string, error) {
    ret := _m.Called(path)

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

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

    return r0, r1
}

requiring you to use this syntax to use value generating functions:

type Nice interface {
   Get(string) (*Profile, error)
}

myNiceMock.On("Get").Return(func(a string) *Profile {
    if a == "hello" {
        return &Profile{}
    }
}, func(a string) error {
    if a == "hello" {
        return nil
    }
})

Because each return value requires its own generating function (just discovered this after reading the source a couple of times!).

Wouldn't it make more sense to have the first method be a single function that returns all the required parameters, instead of requiring the user to define two functions ?

What about doing something like:

func (_m *Requester) Get(path string) (string, error) {
    ret := _m.Called(path)

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

    var r1 error
    r1 = ret.Error(1)

    return r0, r1
}

thus requiring a simpler form to use:

myNiceMock.On("Get").Return(func(a string) (*Profile, error) {
    if a == "hello" {
        return &Profile{}, nil
    }
})

Taking two functions, one for each return value, seems counterintuitive to me.

Generate coded has compile error when argument same as a package name

My interface has an argument which is the same as a package name, event:

type Connector interface {
    Broadcast(event event.Event) error
}

Generated mock:

func (_m *Connector) Broadcast(event event.Event) error {
    ret := _m.Called(event)

    var r0 error
    if rf, ok := ret.Get(0).(func(event.Event) error); ok {
        r0 = rf(event)
    } else {
        r0 = ret.Error(0)
    }

    return r0
}

Fails to compile with:

connector.go:52: event.Event undefined (type event.Event has no field or method Event)

Solution: The generator should always autogenerate argument names (as it does when your interface doesn't provide a name).

Mocks to handle 'nil' return values

Hi,
I have the following method in an interface
getData(name string, version uint8)([]byte, *ErrorObject)
where ErrorObject is a custom type we use for passing errors around.

Two issues

  1. Mockery generates an empty file for this interface.
  2. If it did generate mocks in the usual way ...
    ret := m.Called(name, version)
    r0 := ret.Get(0).([]byte)
    this would panic if the "[]byte" was nil.

This is needed if we have to simulate an error condition in getData where []byte is nil and the ErrorObject is not nil.

Maybe you could fix it this way

var r0 []byte
var r1 *ErrorObject

if args.Get(0) == nil {
    r0 = nil
} else {
    r0 = args.Get(0).([]byte)
}

if args.Get(1) == nil {
    r1 = nil
} else {
    r1 = args.Get(1).(*ErrorObject)
}
return r0, r1

"could not import"

$ mockery -name=Client -case=underscore
Error parsing file:  client_test.go:14:2: could not import github.com/stretchr/testify/assert (can't find import: github.com/t11e/go-pebbleclient/vendor/github.com/stretchr/testify/assert)
Error parsing file:  client_test.go:14:2: could not import github.com/stretchr/testify/assert (can't find import: github.com/t11e/go-pebbleclient/vendor/github.com/stretchr/testify/assert)
Error parsing file:  client_test.go:14:2: could not import github.com/stretchr/testify/assert (can't find import: github.com/t11e/go-pebbleclient/vendor/github.com/stretchr/testify/assert)
Error parsing file:  client_test.go:14:2: could not import github.com/stretchr/testify/assert (can't find import: github.com/t11e/go-pebbleclient/vendor/github.com/stretchr/testify/assert)
Error parsing file:  client_test.go:14:2: could not import github.com/stretchr/testify/assert (can't find import: github.com/t11e/go-pebbleclient/vendor/github.com/stretchr/testify/assert)
Error parsing file:  client_test.go:14:2: could not import github.com/stretchr/testify/assert (can't find import: github.com/t11e/go-pebbleclient/vendor/github.com/stretchr/testify/assert)
Error parsing file:  client_test.go:14:2: could not import github.com/stretchr/testify/assert (can't find import: github.com/t11e/go-pebbleclient/vendor/github.com/stretchr/testify/assert)
Error parsing file:  client_test.go:14:2: could not import github.com/stretchr/testify/assert (can't find import: github.com/t11e/go-pebbleclient/vendor/github.com/stretchr/testify/assert)
Unable to find Client in any go files under this path
exit status 1

$ ls vendor/github.com/stretchr/testify/assert   
assertion_forward.go       assertions.go       doc.go     forward_assertions.go       http_assertions.go
assertion_forward.go.tmpl  assertions_test.go  errors.go  forward_assertions_test.go  http_assertions_test.go

$ pwd
/Users/alex/.go/src/github.com/t11e/go-pebbleclient

$ echo $GOPATH
/Users/alex/.go

Works with every other project I have, just not exactly this one. The project compiles and tests fine, there's nothing unusual about it. Same versions of Mockery and Testify, too.

Errors are swallowed up, making debugging difficult.

in doWalk in walker.go, I tweaked lines 57...:

        err = p.Parse(path)
        fmt.Println("Parse", path)
        if err != nil {
            fmt.Println("Error:", err)
            continue
        }

And running it I now read:

Parse store.go
Error: open .#main.go: no such file or directory

otherwise, it would say nothing, except it didn't find it..

What would be the best way to resurface errors ?

Refactor code to use go/types instead of go/ast

On issue #18 I mentioned that Go 1.5's go/types package I stated that the change should allow simplifying the codebase.

I wanted to see how much work it would mean so I did a quick implementation from scratch using go/types.

The implementation results in ~24% less and the following bugs are fixed: #18 #19 #40

% wc -l $(ls **/*.go | grep -v _test | grep -v fixtures)
      57 main.go
     174 mockery/generator.go
      99 mockery/importer.go
      40 mockery/imports.go
      39 mockery/method.go
     409 total
% wc -l $(ls **/*.go | grep -v _test | grep -v fixtures)
     197 cmd/mockery/mockery.go
       4 doc.go
     254 mockery/generator.go
      81 mockery/parse.go
     536 total

Unable to import mockery

 $ go get -u -v github.com/vektra/mockery
github.com/vektra/mockery (download)
package github.com/vektra/mockery
    imports github.com/vektra/mockery
    imports github.com/vektra/mockery: found packages doc.go (mockery) and mockery_test.go (main) in ~/gopath/src/github.com/vektra/mockery

Option case=underscore not working properly

Hi, I'm having issues with the option "case=underscore", the generated file names aren't what I'm expecting. For example, if I run:

mockery -name=NotifyEvent -case=underscore

I get notifevent.go and I was expecting notify_event.go

Add nil check for pointer return types.

When mocking pointer return values it is often useful in tests to have the mock return nil and verify behavior:

mockObj := new(mock.Object)
mockObj.On("Foo").Return(nil)

In order to handle this, a nil check has to be performed prior to the type assertion in the generated mock code.

-inpkg produces wrong qualified symbols in non-main package

If I use -inpkg and my package name is things, and my interface is Thing, then it generates a file in the correct package, but referencing the original interface as things.Thing:

package things

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

// MockThing is an autogenerated mock type for the Thing type
type MockThing struct {
    mock.Mock
}

// Get provides a mock function with given fields: uid, options
func (_m *Client) Get(uid string, options things.GetOptions) (*things.Item, error) {
    ret := _m.Called(uid, options)
}
[...]

But Go doesn't allow you to qualify symbols in a package with its own package name (things.Item), and running this through goimportsย will of course cause it to import itself.

The correct behaviour is to not prefix the symbols that are in the same package.

Mock for interface{}

Hi,

after recent changes there is no way to generate mock for method that accepts interface{}

Create(value interface{}) error

Output:

Generating mock for: xxx
Unable to generated mock for 'xxx': un-namable type: &types.Interface{methods:[]*types.Func(nil), embeddeds:[]*types.Named(nil), allMethods:[]*types.Func(nil)} (*types.Interface)

Trying to mock consul gives me this error

Generating mock for: ConsulLock
Unable to generated mock for 'ConsulLock': unable to handle type: &ast.StructType{Struct:119, Fields:(*ast.FieldList)(0xc82024d440), Incomplete:false}

Wrong code for methods with varargs

Code generated for Mocks of methods with varargs won't compile. Example:

func (m *Interface) SomeMethod(_a0 Type1, _a1 ...Type2) error {
    ret := m.Called(_a0, _a1)

    var r0 error
    if rf, ok := ret.Get(0).(func(*Type1, ...Type2) error); ok {
        r0 = rf(_a0, _a1)
    } else {
        r0 = ret.Error(0)
    }

    return r0
}

But it should be:

func (m *Interface) SomeMethod(_a0 Type1, _a1 ...Type2) error {
    ret := m.Called(_a0, _a1)

    var r0 error
    if rf, ok := ret.Get(0).(func(*Type1, ...Type2) error); ok {
        r0 = rf(_a0, _a1...)
    } else {
        r0 = ret.Error(0)
    }

    return r0
}

Mockery should allow me to generate multiple interfaces in one line

I've got a bunch of interfaces I'd like to generate but mockery only allows me to specify one per invocation. There's a ton of other interfaces I don't want to generate in the same code paths so I can't do the ... form. Let me just specify multiple paths on the same invocation.

Mocking interface with ellided parameter types doesn't do correct parameter counts:

type Storage interface {
    WriteOpsfile(contents string, reason string) error
}

generates correctly to:

type Storage struct {
    mock.Mock
}

func (m *Storage) WriteOpsfile(contents string, reason string) error {
    ret := m.Called(contents, reason)

    r0 := ret.Error(0)

    return r0
}

However:

type Storage interface {
    WriteOpsfile(contents, reason string) error
}

Generates:

type Storage struct {
    mock.Mock
}
func (m *Storage) WriteOpsfile(contents string) error {
    ret := m.Called(contents)

    r0 := ret.Error(0)

    return r0
}

Notice the generated parameters on WriteOpsfile on the 2nd one.

Build Broken?

I cannot build this package anymore. I believe it's due to the mix of main/mockery packages in the root directory?

edit: I can build it manually. The readme is possibly just out of date.

go install github.com/vektra/mockery/cmd/mockery

Unexpected Method Call

I'm using mockery generated mocks with testify. I'm getting the following error:

mock: Unexpected Method Call
-----------------------------

FindAllOrgs(uint64,uint64,[]string)
        0: 25
        1: 0
        2: []

The closest call I have is: 

FindAllOrgs(uint64,uint64,[]string)
        0: 25
        1: 0
        2: []
 [recovered]
    panic: 

For this test code:

    var limit uint64 = 25
    var offset uint64
    var sort = []string{}
    mock.On("FindAllOrgs", limit, offset, sort).Return([]*api.Org{}, nil)

This is the interface definition:

FindAllOrgs(limit uint64, offset uint64, sortProps []string) ([]*api.Org, error)

The mockery generated implementation:

func (_m *KeyManager) FindAllOrgs(limit uint64, offset uint64, sortProps []string) ([]*api.Org, error) {
    ret := _m.Called(limit, offset, sortProps)

    var r0 []*api.Org
    if rf, ok := ret.Get(0).(func(uint64, uint64, []string) []*api.Org); ok {
        r0 = rf(limit, offset, sortProps)
    } else {
        if ret.Get(0) != nil {
            r0 = ret.Get(0).([]*api.Org)
        }
    }

    var r1 error
    if rf, ok := ret.Get(1).(func(uint64, uint64, []string) error); ok {
        r1 = rf(limit, offset, sortProps)
    } else {
        r1 = ret.Error(1)
    }

    return r0, r1
}

What am I missing / Why is it complaining -- looks the same to me?

Mock file name doesn't have "mock_" prefix and "_test" postfix when mocking an remote interface

Hi there,

I'm using your tool to mock an interface from another package, and I want the file name contains "mock_" prefix and "_test" postfix to indicate its purpose. After digging into your source code, it looks like the generated file cannot have those words in its name unless I use the "-inpkg" option:

func filename(name string) string {
    if *fIP && *fTO {
        return "mock_" + name + "_test.go"
    } else if *fIP {
        return "mock_" + name + ".go"
    }
    return name + ".go"
}

Also looks like the generated struct name cannot have "Mock" in front of it too, unless I specify the -inpkg option:

func (g *Generator) mockName() string {
    if g.ip {
        if ast.IsExported(g.iface.Name) {
            return "Mock" + g.iface.Name
        } else {
            first := true
            return "mock" + strings.Map(func(r rune) rune {
                if first {
                    first = false
                    return unicode.ToUpper(r)
                }
                return r
            }, g.iface.Name)
        }
    }

    return g.iface.Name
}

The reason I don't wanna use the -inpkg option and move the mock file back to my package manually is because I'm doing this in a rake file task, which links to the "mother rakefile" in my workspace for easier dependency management:

file "server/mock_librarian_test.go" => "../librarian/librarian.go" do |t|
    sh "mockery -output server/ -case underscore -dir ../librarian -name Librarian -testonly"
    # mockery could not generate file name with "mock" and "test" from a remote
    # interface, so change file name here manually.
    sh "mv server/librarian.go server/mock_librarian_test.go"
end

task :generate => ["server/mock_librarian_test.go", "server/mock_message_producer_test.go", "api_spec.json-bindata.go"]

I don't know if this is your business logic or not, but it is pretty common for me to mock some external dependencies during unit testing while keep the names of mock structs and file names informative. So are you guys considering changing the naming conventions in the future? Can I make a pull request on this?

Thanks!

"go:generate" requires sh to work?

This works:

//go:generate sh -c "mockery -name='Thing'"

But this:

//go:generate mockery -name='Thing'

fails:

$ go generate ./...
Unable to find Thing' in any go files under this path
event/eventbus/thing.go:10: running "mockery": exit status 1

I've confirmed that the current working directory is correct.

Nested interfaces are ignored when generating mocks

When generating a mock for io.ReadCloser:

// ReadCloser is the interface that groups the basic Read and Close methods.
type ReadCloser interface {
    io.Reader
    io.Closer
}

The following mock was generated, without any of the methods defined in io.Reader and io.Closer:

type ReadCloser struct {
    mock.Mock
}

Not too much work to expand out all of the method definitions myself, but ideally the generator would be able to generate stubs for the nested interfaces.

Mocking interfaces in main namespace

Hi,

I don't know if this is a stupid question or not but is it possible to generate mocks into a mocks "subpackage" when your interfaces are in main?

e.g.

main.go

package main

type Something struct {
}

type MyInterface interface {
     DoSomething() Something //return main.Something
}

func main() {
}

Will generate something like:

mocks/MyInterface.go

package mocks

import "github.com/stretchr/testify/mock"
import "github.com/warmans/example" //tries to import main

type MyInterface struct {
   mock.Mock
}

func (m *MyInterface) DoSomething() main.Something {
    //...
    return main.Something
}

which means the test looks like this:

main_test.go

package main

import (
    "testing"
    "github.com/warmans/example/mocks" //import the mocks subpackage
)

func TestDoSomethingDoesSomething() {
    mock = new(mocks.MyInterface) //create the mock
}

Couple of issues: there is import recursion which causes a import cycle not allowed in test error. Also Go seems to be a bit funny about importing and using main anyway.

I am able to work around the problem by supplying the inpkg=true flag but it seems cleaner to have the mocks subpackage.

Thanks

Embedded interfaces aren't expanded

For example:

type A interface {
  MethodInA()
}
type B interface {
  A
  MethodInB()
}

If you run Mockery on B, it mocks MethodInB but not MethodInA.

New parsing seems to be unable to join across files in the same package

It may be bad style but I've got a package called fips, and in there I have 2 files:

fips1.go

type IFIPS interface {
   GetValues() (string, error)
}

type FIPS struct {
  Client IFIPS
}

func NewFIPS() {
  return &FIPS{
    Client: newSubFips(),
  }
}

And fips2:

type SubFips struct {
}

func (this *SubFips) GetValues (string, error) {
  return "hi", nil
}

func newSubFips() *SubFips {
  return &SubFips{}
}

When I run this code (or somthign like it) I get:
parse(fips/fips1.go): xxx/yyy: undeclared name: newSubFips

It seems like the new parser is trying to understand cross file issues.

I'm also now getting lots of "could not import github.com/gaffo/fips/fips (can't find import: )"

So I'm not actually getting any mocks generating on my big project now because I think the new parsing is failing out early on lots of stuff.

Mocks for interfaces which return named nillable types do not have nil checks

Example:

package main
type B interface {
  Bar()
}
type A interface {
  Get() B
}

Running mockery -name A -print on this does not yield a mock which checks for nil! The problem is that the B return type is parsed to an *ast.Ident, not an *ast.InterfaceType (and therefore isNillable returns false).

You can use the type of the identifier to handle this case, e.g.:

func (g *Generator) isNillable(typ ast.Expr) bool {
        switch t := typ.(type) {
        case *ast.StarExpr, *ast.ArrayType, *ast.MapType, *ast.InterfaceType, *ast.FuncType, *ast.ChanType:
                return true
        case *ast.Ident:
                switch d := t.Obj.Decl.(type) {
                case *ast.TypeSpec:
                        switch d.Type.(type) {
                        case *ast.StarExpr, *ast.ArrayType, *ast.MapType, *ast.InterfaceType, *ast.FuncType, *ast.ChanType:
                                return true
                        }
                }
        }
        return false
}

Methods with ... params generate broken mocks.

This is a regression sometime since SHA a43d734f241595. Not sure exactly when.

The following interface will generate a mock that doesn't compile:

 type MyInterface interface {
   WriteItems(uuid string, values ...string) error
 }

The old "working" code generated code that probably wasn't mockable, but it wasn't blocking.

This generates:

func (_m *MyInterface) WriteItems(uuid string, values ...string) error {
ret := _m.Called(uuid, values)
var r0 error
if rf, ok := ret.Get(0).(func(string, ...string) error); ok {
    r0 = rf(uuid, values)
} else {
    r0 = ret.Error(0)
    }
return r0
}

Which results in:

 mocks/MyInterface.go:14: cannot use values (type []string) as type string in argument to rf

I think Line 14 needs to be:

        r0 = rf(uuid, values...)

Cannot generate mock for context.Context

Copied this interface into my code and tried to generate a mock, failed with an error:

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key interface{}) interface{}
}
$ mockery -name=Context
Generating mock for: Context
Unable to generated mock for 'Context': unable to handle type: &ast.StructType{Struct:1473, Fields:(*ast.FieldList)(0x8206f8ff0), Incomplete:false}

Install broken: golang.org/x/tools/astutil has disappeared

It looks like the golang.org/x/tools/astutil repo has been deleted. This breaks fresh installs of mockery.

Repro:

go get github.com/vektra/mockery

Expected behavior: Mockery is silently installed

Actual behavior: install fails with the following error:

 package github.com/vektra/mockery
    imports code.google.com/p/go.tools/astutil
    imports code.google.com/p/go.tools/imports
    imports golang.org/x/tools/astutil
    imports golang.org/x/tools/astutil
    imports golang.org/x/tools/astutil: cannot find package "golang.org/x/tools/astutil" in any of:
    /usr/local/go/src/pkg/golang.org/x/tools/astutil (from $GOROOT)
    /Users/{username}/go/src/golang.org/x/tools/astutil (from $GOPATH)

Attempts to install astutil direct also fail and the golang.org and github locations for the package return 404s.

Naming convention of generated mock objects

I have a scenario like the following:

I defined an interface in a package. Mockery generated a mock object in "mocks" package with the same name.
Typically tests should be written in the same package they are testing - I can't seem to get code coverage to work properly if I don't do it this way. So I tried importing the mock object in the test - but the mock object had imports from my code, resulting in a circular reference. I ended up having to move the mock object into the same package and rename it. It would be nice if mockery could generate mocks so that:

  1. the mock for interface Foo becomes mock struct MockFoo
  2. the mock is placed in the same package as the interface

I saw an -output argument for mockery, but was unable to get it to output to the current directory:

mockery -name=WebUserService -output=.
Generating mock for: WebUserService
Error writing WebUserService: mock.go:1:9: expected 'IDENT', found '.' (and 1 more errors)

README.md example not working as expected

I want to mock out a method that needs to respond with different return values and make assertions about its parameters. The example in the README looked like it does exactly what I want. However, I was unable to get mockery (or Testify more accurately) to run my lambda function and return its return values.

Here's the closest I could come to following the instructions:
https://github.com/brycefisher/mockerytest

Am I doing something wrong here? It feels like I'm following the directions from the README. Thanks for your help!!

Interfaces returning interfaces

Hi,

A recent commit (I suspect fe07b98) appears to have broken mocks of interfaces which in turn return interfaces. Eg, given:

package interfaces

type B interface {
  Bar()
}
type A interface {
  Get() B
}

The generated mock for A now looks like:

package mocks

func (a *A) Get() B {
 // Note that B is mocks.B
 ...
}

where previously it was:

func (a *A) Get() interfaces.B {
 ...
}

Thanks for a useful tool.

mockery -all failing on windows OS

When i try to generate mocks for my project on a windows box, I get the below error:
mockery -all
Error writing XXXX: mock.go:3:27: unknown escape sequence

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.

Broken file loading

bb38420 breaks generating mocks from within a package which also imports those mocks.

Consider the following foo package:

foo.go:

package foo

type FooInterface interface {
    FooFunc()
}

foo_test.go:

package foo

import "mocks" // Tests for foo depend on the mock

func Test() {
    f := &mocks.FooInterface{}
    f.FooFunc()
}

Previously, (at b08b323) the mock would be generated:

$ mockery --name=FooInterface
Generating mock for: FooInterface

However, after commit bb38420, the mocks are no longer generated (presumably the import of foo_test.go fails, because the mock hasn't been generated yet):

$ mockery --name=FooInterface
Unable to find FooInterface in any go files under this path

gist containing the files are here:
https://gist.github.com/dansimau/743bb5ea1e94355402d2e4e88b1d3f68

mocks for interfaces with composition are missing methods

Given the following interface:

package test

import "io"

type ReadCloser interface {
        io.Reader
        Close() error
}

Expected:

type ReadCloser struct {
        mock.Mock
}

func (m *ReadCloser) Read(p []byte) (int, error) {
        ret := m.Called(p)

        r0 := ret.Get(0).(int)
        r1 := ret.Error(1)

        return r0, r1
}
func (m *ReadCloser) Close() error {
        ret := m.Called()

        r0 := ret.Error(0)

        return r0
}

Generated:

type ReadCloser struct {
        mock.Mock
}

func (m *ReadCloser) Close() error {
        ret := m.Called()

        r0 := ret.Error(0)

        return r0
}

Not working for a type

mockery -dir=$GOPATH/src/github.com/Shopify/sarama -name=AsyncProducer
Generating mock for: AsyncProducer
Unable to generated mock for 'AsyncProducer': unable to handle type: &ast.ChanType{Begin:1463, Arrow:1467, Dir:1, Value:(*ast.StarExpr)(0x2083eea40)}

Error when generating Mock with a function as parameter

type Fooer interface {
Foo(func(x string) string) string
}
mockery fails with the following error:
Generating mock for: Fooer
Unable to generated mock for 'Fooer': unable to handle type: &ast.FuncType{Func:43, Params:(_ast.FieldList)(0xc208026960), Results:(_ast.FieldList)(0xc208026990)}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.