Creating Stubs with gomock

Andrew Poydence
1 min readNov 25, 2018

gomock is able to create a stub just as well as a mock. If you want a stub that will always return a value for a given method call you use the AnyTimes() method:

ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockFoo(ctrl)
m.
EXPECT().
Bar(gomock.Any()).
Return(55).
AnyTimes()

This will return 55 for any call to Bar(). But what if you need something a little more complex? What if you need it to return 66 if you pass in 6? Well gomock can easily do that as well!

ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockFoo(ctrl)
m.
EXPECT().
Bar(gomock.Eq(6)).
Return(66).
AnyTimes()
m.
EXPECT().
Bar(gomock.Any()).
Return(55).
AnyTimes()

Note: The gomock.Any() case must be last. gomock keeps a slice of matchers (e.g., Any() vs Eq()) and then iterates over each . The gomock.Any() will always return true.

--

--

Andrew Poydence

#Cloud Developer at @Google. I am love with writing #Go, exploring #GCP and the cloud in general. Opinions stated here are my own.