Is it possible to mock a function imported from a package in golang?

前端 未结 3 1592
旧时难觅i
旧时难觅i 2020-12-23 10:18

I have the following method to test, which uses a function imported from a package.

import x.y.z

func abc() {
    ...
    v := z.SomeFunc()
    ... 
}
         


        
3条回答
  •  温柔的废话
    2020-12-23 10:38

    One thing you can do is this:

    import "x/y/z"
    
    var someFunc = z.SomeFunc
    
    func abc() {
        ...
        v := someFunc()
        ... 
    }
    

    And in your test file you would do this.

    func Test_abc() {
        someFunc = mockFunc
        abc()
    }
    

    But make sure that you do this in a concurrent manner, if you have multiple TestXxx functions calling abc or setting someFunc you may be better of using a struct with a someFunc field.

提交回复
热议问题