testify icon indicating copy to clipboard operation
testify copied to clipboard

Allow returnArguments to be generated on the fly

Open muudyguy opened this issue 8 years ago • 2 comments

Hi,

In our code base we sometimes have functions declared as arguments in the interfaces, and these functions are run during the execution and affect the returned error from the interface function. Example:

DoSomething(context.Context, func(p AnotherInput) error) error

If the function input returns an error, this will be reflected to the root error returned from DoSomething. This makes it rather difficult to test it with the existing tools. To compensate I have done this :

s.mockedInterface.On("DoSomething", mock.Anything, mock.Anything).
        ReturnWithFunc(func(arguments mock.Arguments) []interface{} {
		f := arguments[2].(func(tx AnotherInput) error)
		err := f(AnotherInput{})
		return []interface{}{
			err,
		}
	})

Was there an already existing method to do something like this, or should I maybe open a pull request with this new utility ?

Also potentially, the way I am trying to test could be too broad, and the input function could be tested separately. But regardless.

muudyguy avatar Sep 03 '18 10:09 muudyguy

Closing because, i discovered you can do this already, albeit it is quite obscure

muudyguy avatar Sep 03 '18 12:09 muudyguy

For other readers, the way to do it is https://github.com/stretchr/testify/issues/292. This is very unintuitive and not documented as far as I can find, but is easy enough.

raxod502 avatar Dec 10 '22 03:12 raxod502