testify icon indicating copy to clipboard operation
testify copied to clipboard

Unexpected call when interface is parameter

Open amerpersonal opened this issue 1 year ago • 3 comments

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

amerpersonal avatar Feb 01 '24 17:02 amerpersonal

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)
}

tscales avatar Feb 02 '24 17:02 tscales

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?

brackendawson avatar Feb 02 '24 18:02 brackendawson

I confirm what @tscales said, i can't reproduce the issue either. Here is a working snippet

st3penta avatar Feb 17 '24 16:02 st3penta

Please comment again, or start a discussion (tab up top), if you still have this problem.

brackendawson avatar Feb 26 '24 13:02 brackendawson