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?
I tried with this and works:
type Foo struct {
mock.Mock
}
func (m *Foo) Bar() {
m.Called()
}
func TestFoo(t *testing.T) {
m := &Foo{}
m.On("Bar").Return(nil)
m.Bar()
m.AssertCalled(t, "Bar")
}
As stated by Chris Drew, you've to use a receiver pointer on Bar method's declaration.
Additionally, you've to istantiate a new structure as pointer and mock the method to return a value.
Looking at the documentation of testify I think you have to explicitly call func (*Mock) Called
to tell the mock object that a method has been called.
func (m *Foo) Bar() {
m.Called()
}
There are some examples in the testify tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With