stretchr / testify

A toolkit with common assertions and mocks that plays nicely with the standard library
MIT License
23.11k stars 1.58k forks source link

Not specifying arguments to mock causes index out of range error #373

Open seppestas opened 7 years ago

seppestas commented 7 years ago

When mocking a function that takes arguments, not specifying those arguments causes the test to panic with following error: "runtime error: index out of range". Example

A message stating the mock was called with closestCall.Arguments instead of no arguments would be a lot nicer.

Not specifying the function arguments is an obvious mistake when the developer intends to write a test where the arguments can be anything. In this case mock.Anything should be used since not specifying the arguments means the mock is expected to be called without arguments. IMO this is not very clear though, the Mock.On method is way less descriptive than E.g gomock's MockMatcher, which requires to explicitly state the excepted arguments using 'MockMatcher.EXCEPT'.

Personally, I think setting the return value of a mocked function and checking it's arguments should be split, allowing to separate test set up and assertions more clearly.

leplatrem commented 6 years ago

Thank you for opening this issue!

It took me a very long time to figure out that the panic on index out of range was due to the call of On(...)

I had to replace:

v.On("ExtractClaims").Return(claims, nil)

to

v.On("ExtractClaims", mock.Anything).Return(claims, nil)

I guess it would help if the introductory example in the docs would show a full assertion (eg. with a On(...).Return(...) and an AssertCalled())

agraffm commented 4 years ago

👍 for adding something to the docs which would indicate this