0

Package A

func Validate(){
    db.CheckPresent() //how to mock this function which is in another package
    return nil
}

I am writing test case in Golang to test a function which calls CheckPresent() function from another package. How to mock CheckPresent() fuction?

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • 2
    You can't. You'd need to either wrap it in a type with an interface you can mock, or put the function in a variable so you can swap out the implementation for testing. – Adrian Feb 15 '19 at 20:29
  • 1
    Possible duplicate of [Mock functions in Go](https://stackoverflow.com/questions/19167970/mock-functions-in-go) – Jonathan Hall Feb 15 '19 at 21:12

1 Answers1

0
type Checker interface {
    CheckPresent()
}

// mock
type checkerMock struct {
}

func (m checkerMock) CheckPresent() {
}

// production code
type handler struct {
    db Checker
}

func New(db Checker) *handler {
    return &handler{
        db: db,
    }
}

func (h handler) Validate() {
    h.db.CheckPresent() 
    return nil
}
Dmitry Harnitski
  • 5,838
  • 1
  • 28
  • 43