我正在使用 testify 来测试我的代码,我想检查是否调用了一个函数。
我正在做以下事情:
type Foo struct {
mock.Mock
}
func (m Foo) Bar() {
}
func TestFoo(t *testing.T) {
m := Foo{}
m.Bar()
m.AssertCalled(t, "Bar")
}
我得到的错误:
Error: Should be true
Messages: The "Bar" method should have been called with 0 argument(s), but was not.
mock.go:419: []
我调用函数“Bar”并立即询问它是否被调用但它返回 false。 我究竟做错了什么? 测试一个函数是否被 testify 调用的正确方法是什么?
最佳答案
我试过这个并且有效:
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")
}
如 Chris Drew 所述,您必须在 Bar 方法的声明中使用接收器指针。
此外,您必须将一个新结构实例化为指针并模拟该方法以返回一个值。
关于go - AssertCalled 总是因 testify 库而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44365009/