0

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.

ExceptionHandler
  • 213
  • 1
  • 8
  • 24
  • Which logging library you are using? standard `log` or `logrus` or another library? Also in the `TestNil()` method where is `s` variable definition? Are you sure `TestNil` does not contain any `*testing.T` argument? – Shalauddin Ahamad Shuza Apr 25 '19 at 06:44

1 Answers1

1

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

func (m *MyMockedObject)LogNilValue(ctx string) {
    args := m.Called(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)
}
Brad
  • 958
  • 8
  • 21