如何模拟另一个包中的函数?

时间:2019-02-15 20:21:01

标签: go

套餐A

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

我正在用Golang编写测试用例,以测试从另一个包调用CheckPresent()函数的函数。如何模拟CheckPresent()功能?

1 个答案:

答案 0 :(得分: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
}