Golang Mockery - Mock Function with multiple return values
If you've ever written a test in golang, you may used the testify package. An immensely useful extension of that is the mockery package, which gives you the ability to autogenerate mocks for interfaces with ease.
In most cases, you'll want your mock functions to return simple uncomputed values. There may be some cases you want to do something more complicated to determine the return value.
The example from the mockery documentation:
Mock.On("MyFunctionName", mock.AnythingOfType("string")).
Return(func(s string) string {
return s
})
But if you've ever tried to use this for a function with multiple return values, you might assume you just get an error for:
Mock.On("MyFunctionName", mock.AnythingOfType("string")).
Return(func(s string) (string, error) {
return s, errors.New("error")
})
panic: interface conversion: interface {} is
func(string) (string, error), not string [recovered]
Solution
The documentation isn't clear on this, but in order to handle multiple value return functions, you actually pass through two functions, one for each return value:
Mock.On("MyFunctionName", mock.AnythingOfType("string")).
Return(func(s string) string {
return s
}, func (s string) error {
return errors.New("error")
})