go - AssertCalled 总是因 testify 库而失败

标签 go testify

我正在使用 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/

相关文章:

go - 在结构的字段上实现 Redigo Scanner 接口(interface)

json - 将 JSON 解析为结构

git - 使用 Git(或任何 VCS)的 Go 项目的正确组织是什么?

go - 从包函数返回 Mock

string - 字符串.Builder的内存使用情况

go - 在锁定之前推迟解锁是否可以

go - 如何使用 testify/mock 在 golang 中模拟数据库层

unit-testing - testify包错误 `The code you are testing needs to make 1 more call(s)`

unit-testing - 错误 : suite. go:61: test paniced: reflect: Call with too few input arguments

unit-testing - 使用 PanicsWithValue 进行 Golang 单元测试