Mock#
Generates a mock implementation for an interface (not structs) — each method becomes a <Method>Func field plus a <Method>Called counter, so you can both stub behavior and assert call counts. Enabled by default; disable with -mock=false.
gcraft generate -type Notifier -src ./notifier.gotype Notifier interface {
Send(to, message string) error
}Generates:
type MockNotifier struct {
SendFunc func(to string, message string) error
SendCalled int
}
func (m *MockNotifier) Send(to string, message string) error {
m.SendCalled++
if m.SendFunc != nil {
return m.SendFunc(to, message)
}
return nil
}Usage in a test:
mock := &MockNotifier{
SendFunc: func(to, message string) error {
return nil
},
}
svc.Notify(mock) // svc takes a Notifier
if mock.SendCalled != 1 {
t.Errorf("expected Send to be called once, got %d", mock.SendCalled)
}