Mockery: Mock Return Value Provider Function With Multiple Values

If you've ever written a test in golang, chances are you've used the testify package to make writing tests a breeze. An immensely useful extension of that is the mockery package, which gives you the ability to autogenerate testify mocks for interfaces with ease.

Whilst in most cases, you'll want your mock functions to return simple uncomputed arguements, there may be some cases you want to do something a little more complicated to determine the return vaue. The example from the mockery documentation is the case where you have a pass-through function that needs to be aware of the arguement in order to pass it though.

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

This is great, but if you've ever tried to use this for a function with multiple return values, you might assume you just need to do the following:

Mock.On("passthrough", mock.AnythingOfType("string")).Return(func(s string) (string, error) {
    return s, errors.New("error")
})

However, you'd probably get this error:

panic: interface conversion: interface {} is func(string) (string, error), not string [recovered] panic: interface conversion: interface {} is func(string) (string, error), not string

The Solution

The documentation isn't clear on this, but in order to handle multiple value return functions, you don't return both values in a single function, you actually pass through two functions, one for each return value.

Mock.On("passthrough", mock.AnythingOfType("string")).Return(func(s string) string {
return s
}, func (s string) error {
return errors.New("error")
})

This isn't completely clear and a pull request was rejected to replace it with the more implicit syntax. But beyond this little weirdness, the package is great and well worth including in any golang project.

Posted on Oct 03, 2018

Discuss This

blog comments powered by Disqus