golang / mock

GoMock is a mocking framework for the Go programming language.
Apache License 2.0
9.29k stars 610 forks source link

Add opportunity to substitute default matcher #592

Open tsamsiyu opened 2 years ago

tsamsiyu commented 2 years ago

Requested feature Provide possibility to setup default Matcher so you would not need to wrap all your arguments into your custom matcher.

Why the feature is needed When you have hundreds of tests and tens of microservices it's very helpful to have a default matcher and not wrap each call manually.

(Optional) Proposed solution Adding this as easy as add new property to Controller and pass it further PR: https://github.com/golang/mock/pull/581/files

codyoss commented 2 years ago

Hey @tsamsiyu thanks for opening up this issue. Sorry I did not notice this linked to a PR(just closed it). Could you provide some code samples of what pseudo-code of what this looks like today and what it cloud looks like after your proposed request. Thanks!

tsamsiyu commented 2 years ago

in the middle of a generated mock:

...
func (m *MyMock) CallMe(arg0, arg1 interface{}) *gomock.Call {
    m.mock.ctrl.T.Helper()
    return m.mock.ctrl.RecordCallWithMethodType(m.mock, "CallMe", reflect.TypeOf((*MyMock)(nil).CallMe), arg0, arg1)
}
...

it's used like in the following example:

...
myMock.EXPECT().CallMe(gomock.Any(), foo)
myMock.EXPECT().CallMe(gomock.Any(), bar)
myMock.EXPECT().CallMe(gomock.Any(), baz)
myMock.EXPECT().CallMe(gomock.Any(), que)
...

in order to apply our own matcher we have to do the next:

...
myMock.EXPECT().CallMe(gomock.Any(), test.CustomMatch(foo))
myMock.EXPECT().CallMe(gomock.Any(), test.CustomMatch(bar))
myMock.EXPECT().CallMe(gomock.Any(), test.CustomMatch(baz))
myMock.EXPECT().CallMe(gomock.Any(), test.CustomMatch(que))
...

to make it easier for different teams we want to create our custom matcher and provide it once, like this:

ctrl := gomock.NewController()
ctrl.ArgMatcher = test.NewCustomMatcher()
myMock := test.NewMyMock(ctrl)

The thing is that we have hundreds of tests in different microservices and we would prefer to do it at one place and it would also help us to keep code cleaner.

codyoss commented 2 years ago

Thanks for the detailed response. This is an interesting use case. I would like to leave this issue open a bit and see if others have this sort of need as well. There have been thoughts in the past to create another constructor for the ctrl that accepts some options to configure mocks behavior. This seems like a good fit for such a thing.