doujiebo9849 2019-04-24 12:50
浏览 16

Testify模拟正在返回断言该函数尚未被调用

My tests keep failing with but no actual calls happened but I am positive the func is getting called (It's a logging function so I see the logs on the terminal)

Basically I have code that looks something like this :

common/utils.go


func LogNilValue(ctx string){
    log.Logger.Warn(ctx)
}

main.go


import (
"common/utils"
)

func CheckFunc(*string value) {
    ctx := "Some context string"
    if value == nil {
    utils.LogNilValue(ctx) //void func that just logs the string
   }
}

test.go


type MyMockedObject struct{
    mock.Mock
}

func TestNil() {
    m := new(MyMockedObject)
    m.Mock.On("LogNilValue", mock.Anything).Return(nil)
    CheckFunc(nil)
    m.AssertCalled(s.T(), "LogNilValue", mock.Anything)
}

I expect this to work but then, I keep getting no actual calls happened. Not sure what I am doing wrong here.

  • 写回答

1条回答 默认 最新

  • duanqiang5722 2019-04-25 07:35
    关注

    LogNilValue should have MyMockedObject as the method receiver, in order to mock the method. Something like this

    func (*MyMockedObject)LogNilValue(ctx string) {
        log.Logger.Warn(ctx)
    }
    

    CheckFunc should look like this:

    func CheckFunc(value *string, m *MyMockedObject) {
        ctx := "Some context string"
        if value == nil {
            m.LogNilValue(ctx) //void func that just logs the string
       }
    }
    

    And finally the TestNil method:

    func TestNil() {
        m := new(MyMockedObject)
        m.Mock.On("LogNilValue", mock.Anything).Return(nil)
        CheckFunc(nil, m)
        m.AssertCalled(s.T(), "LogNilValue", mock.Anything)
    }
    
    评论

报告相同问题?