簡體   English   中英

AssertCalled總是以testify庫失敗

[英]AssertCalled always fails with testify library

我正在使用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方法的聲明中使用接收器指針。

此外,您必須將新結構作為指針進行異步並模擬返回值的方法。

查看testify的文檔我認為你必須顯式調用func (*Mock) Called來告訴mock對象已經調用了一個方法。

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

在作證測試中有一些例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM