Skip to content

Instantly share code, notes, and snippets.

@sebdah
Created January 7, 2017 01:19
Show Gist options
  • Save sebdah/fca9e3a8e26c0c9ea8d8b01aecc22897 to your computer and use it in GitHub Desktop.
Save sebdah/fca9e3a8e26c0c9ea8d8b01aecc22897 to your computer and use it in GitHub Desktop.
Mockery example
package messager
// Messager is a struct handling messaging of various types.
type Messager struct {
sms SMS
}
// SendHelloWorld sends a Hello world SMS.
func (m *Messager) SendHelloWorld(number int) error {
err := m.sms.Send(number, "Hello, world!")
if err != nil {
return err
}
return nil
}
package messager
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSendHelloWorld(t *testing.T) {
sampleErr := errors.New("some error")
tests := map[string]struct {
number int
smsErr error
err error
}{
"successful": {0132423444, nil, nil},
"propagates error": {0132423444, sampleErr, sampleErr},
}
for _, test := range tests {
sms := &MockSMS{}
sms.On("Send", test.number, "Hello, world!").Return(test.smsErr).Once()
m := &Messager{
sms: sms,
}
err := m.SendHelloWorld(test.number)
assert.Equal(t, test.err, err)
sms.AssertExpectations(t)
}
}
package messager
import mock "github.com/stretchr/testify/mock"
// MockSMS is an autogenerated mock type for the SMS type
type MockSMS struct {
mock.Mock
}
// Send provides a mock function with given fields: number, text
func (_m *MockSMS) Send(number int, text string) error {
ret := _m.Called(number, text)
var r0 error
if rf, ok := ret.Get(0).(func(int, string) error); ok {
r0 = rf(number, text)
} else {
r0 = ret.Error(0)
}
return r0
}
var _ SMS = (*MockSMS)(nil)
package messager
// SMS is an example interface.
type SMS interface {
Send(number int, text string) error
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment