To use mocks in your tests, initialize a controller with gomock.NewController(t) and instantiate the mock using the generated constructor (e.g., NewMockFoo).
For Assertions (Mocks): Use .EXPECT() to define expected calls and .Return() to specify return values.
For Behavior (Stubs): Use .EXPECT() with .DoAndReturn() to execute custom logic or .AnyTimes() to allow multiple calls without strict assertion.
type Foo interface {
Bar(x int) int
}
func SUT(f Foo) {
// ...
}
// Mock Example (with assertions)
func TestFoo(t *testing.T) {
ctrl := gomock.NewController(t)
m := NewMockFoo(ctrl)
m.EXPECT().
Bar(gomock.Eq(99)).
Return(101)
SUT(m)
}
// Stub Example (with custom behavior)
func TestFooStub(t *testing.T) {
ctrl := gomock.NewController(t)
m := NewMockFoo(ctrl)
m.EXPECT().
Bar(gomock.Eq(99)).
DoAndReturn(func(_ int) int {
time.Sleep(1*time.Second)
return 101
}).
AnyTimes()
SUT(m)
}