testify
testify copied to clipboard
Unexpected call when interface is parameter
Hi,
I am experiencing the following error
assert: mock: I don't know what to return because the method call was unexpected.
Either do Mock.On("Send").Return(...) first, or remove the Send() call.
This method was unexpected:
Send(services.ConfirmAccountEmail,repository.User)
Mailer interface:
type Mailer interface {
Send(email Email, receiver User) error
}
Email is also an interface
Test:
type MockMailer struct {
mock.Mock
}
func (m *MockMailer) Send(email Email, receiver User) error {
args := m.Called(email, receiver)
return args.Error(0)
}
In test:
mailer := new(MockMailer)
mailer.On("Send", mock.Anything, mock.Anything).Return(nil)
//Execute the code that is calling send method
Debugging shows that it entered send method, but I still have this error
Could it be that interface is creating an issue? Or maybe mock.Anything?
Thanks
I tried reproducing based on your code was unable to. The following test passes for me.
type Email interface{}
type Mailer interface {
Send(email Email, receiver string)
}
type MockMailer struct {
mock.Mock
}
func (m *MockMailer) Send(email Email, receiver string) error {
args := m.Called(email, receiver)
return args.Error(0)
}
func TestMailer(t *testing.T) {
mailer := new(MockMailer)
mailer.On("Send", mock.Anything, mock.Anything).Return(nil)
err := mailer.Send("hello", "world")
assert.NoError(t, err)
}
You've most likely either missed this line from your test:
mailer.On("Send", mock.Anything, mock.Anything).Return(nil)
or misspelled "Send"
, or your test was using a different mailer mock instance than you expected.
Can you make a minimal compilable example that fails?
I confirm what @tscales said, i can't reproduce the issue either. Here is a working snippet
Please comment again, or start a discussion (tab up top), if you still have this problem.