On 05/04/2017 18:06, Jonathan Yu wrote:
> Hi everyone,
>
> I've been using gomock to generate mock objects (in source mode), and
> it's
> been pretty great - way better than maintaining similar code on my own.
> One
> thing that I find curious, though, is that expectations are recorded
> using
> a generic interface{} type, rather than the original type.
>
> For example, in the sample mock_user.go
> <
https://github.com/golang/mock/blob/master/sample/mock_user/mock_user.go>
> file, we have:
>
> func (_m *MockIndex) Anon(_param0 string) {
> _m.ctrl.Call(_m, "Anon", _param0)
> }
>
> func (_mr *_MockIndexRecorder) Anon(arg0 interface{}) *gomock.Call {
> return _mr.mock.ctrl.RecordCall(_mr.mock, "Anon", arg0)
> }
>
> Does anyone know why the Recorder interface is generated with
> interface{}?
> Doesn't this mean that we lose type safety when defining expectations?
> After all, you can do: mock.EXPECT().Anon(123) even though the method
> must
> be called with a string parameter, right?
Because you _don't_ have to use a value of the appropriate type when
setting up the expectations, e.g.:
"mock.EXPECT().Anon(gmock.Any())" or
"mock.EXPECT().Anon(gomock.Not("invalid"))"
in fact "mock.EXPECT().Anon("123")" is actually a shortcut for
"mock.EXPECT.Anon(gomock.Eq("123"))"
(see
https://godoc.org/github.com/golang/mock/gomock#Matcher)
HTH,
--
Julian