AssertCalled always fails with testify library

Viewed 8780

I am using testify to test my code and I want to check if a function was called.

I am doing the following:

type Foo struct {
    mock.Mock
}

func (m Foo) Bar() {

}

func TestFoo(t *testing.T) {
    m := Foo{}
    m.Bar()
    m.AssertCalled(t, "Bar")
}

The error I am getting:

Error:      Should be true
Messages:   The "Bar" method should have been called with 0 argument(s), but was not.

mock.go:419: []

I call function "Bar" and immediately ask if it was called but it returns false. What am I doing wrong? What is the proper way to test if a function was called with testify?

4 Answers

Make sure it is pointer receiver NOT value receiver.

This will always have nil Calls

type Foo struct {
    mock.Mock
}

func (m Foo) Bar() 
    m.Called()
}

This will have N number of Calls

type Foo struct {
    mock.Mock
}

func (m *Foo) Bar() 
    m.Called()
}

As an additional solution for when you want/need to use a value receiver, though not as clean, specifying Mock as a pointer field worked for me.

type Foo struct {
    m *mock.Mock
}

func (f Foo) Bar() {
    f.m.Called()
}

func TestFoo(t *testing.T) {
    f := Foo{m: &mock.Mock{}}
    f.Bar()
    f.m.AssertCalled(t, "Bar")
}
Related