stretchr / testify

A toolkit with common assertions and mocks that plays nicely with the standard library
MIT License
23.15k stars 1.59k forks source link

Unexpected call when interface is parameter #1528

Closed amerpersonal closed 7 months ago

amerpersonal commented 8 months ago

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

tscales commented 8 months ago

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)
}
brackendawson commented 8 months ago

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?

st3penta commented 7 months ago

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

brackendawson commented 7 months ago

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