Closed abshierjoel closed 9 months ago
@abshierjoel can we close this issue now that https://github.com/uber-go/mock/pull/63 has landed?
Closing now that https://github.com/uber-go/mock/pull/63 has landed.
@r-hang apologies on the late reply -- I've been away this past week. Thank you much!
Problem Statement
While testing functions with multiple calls to the same method, occasionally we encounter a situation where we require multiple matches for one parameter. One approach would be to create multiple
mock.EXPECT()
calls for each distinct match, however, with the newgomock.WithOverridableExpectations()
, the second call will override the first, regardless of any inclusion of.Times(x)
.Regardless of the existing problem with
gomock.WithOverridableExpectations()
, in some situations it would be convenient to create multiple matches from a singleEXPECT
, especially if theDoAnyReturn()
is complex. So I believe this would help ease-of-use.Proposal
Include a new
OneOf
Matcher that will match if a given parameter belongs to the provided list. This will allow for multiple calls to be matched in oneEXPECT()
withTIMES(N)
, which temporarily helps solve the Override issue. In addition to this, being able to match one element against a list would be valuable and improve the ease of use when testing if a parameter matches within a given list.Examples
Example A: Overriding Order
Consider the following function:
Assume we have created an
EXPECT()
forDo()
and would like to later override it as follows:However, with
gomock.WithOverridableExpectations()
enabled, the 2ndEXPECT()
takes precedent and the test fails. One solution to this would then be the following:This approach allows us to use only one
EXPECT
call, but requires that we use anAny()
Matcher and a defaultfalse
case for theDoAndReturn
. It would be preferable to be able to match on if the element was part of a list of acceptable parameter values, as follows:Example B: Mocking Convenience
Consider the following function used to determine which animal food you should use, based on your country:
It may be convenient to stub the call to
GetFood
for any validAnimal
type given. We can do this similarly to above, with aDoAnyReturn
, but this again would require using anAny
matcher. It would be preferable to be able to provide a list of valid matches, as follows:Proposed implementation
I drafted a PR with my proposed implementation in #91