Golang monkey patching

When I have run into this situation my approach is to use my own interface as a wrapper which allows mocking in tests. For example.

type MyInterface interface {
    DoSomething(i int) error
    DoSomethingElse() ([]int, error)
}

type Concrete struct {
    client *somepackage.Client
}

func (c *Concrete) DoSomething(i int) error {
    return c.client.DoSomething(i)
}

func (c *Concrete) DoSomethingElse() ([]int, error) {
    return c.client.DoSomethingElse()
}

Now you can mock the Concrete in the same way you would mock somepackage.Client if it too were an interface.

As pointed out in the comments below by @elithrar, you can embed the type you want to mock so you are only forced to add methods which need mocking. For example:

type Concrete struct {
    *somepackage.Client
}

When done like that, additional methods like DoSomethingNotNeedingMocking could be called directly on Concrete without having to add it to the interface / mock it out.


There is an available monkey patching library for Go. It only works for Intel/AMD systems (targeting OSX and Ubuntu in particular).