【问题标题】:Testify mock is returning assertion that the function has not been calledTestify mock 正在返回该函数尚未被调用的断言
【发布时间】:2019-04-24 12:50:29
【问题描述】:

我的测试一直失败,但 no actual calls happened 但我肯定 func 正在被调用(这是一个日志记录功能,所以我在终端上看到了日志)

基本上我的代码看起来像这样:

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)
}

我希望这能奏效,但我不断收到no actual calls happened。不知道我在这里做错了什么。

【问题讨论】:

  • 您使用的是哪个日志库?标准loglogrus 或其他库?同样在TestNil() 方法中s 变量定义在哪里?你确定TestNil 不包含任何*testing.T 参数吗?

标签: go mocking testify


【解决方案1】:

LogNilValue 应该有 MyMockedObject 作为方法接收器,以便模拟方法。像这样的

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

CheckFunc 应如下所示:

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

最后是TestNil 方法:

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

【讨论】:

    猜你喜欢
    • 2012-08-24
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多