Golang monkey patching

北城以北 提交于 2019-11-30 19:00:24
sberry

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).

Depending on the situation, you can apply the "Dependency Inversion Principle" and leverage Go's implicit interfaces.

To do this, you define an interface of your requirements in the package with the usage (as opposed to defining what you provide in the package that implements it; like you might in Java).

Then you can test your code in isolation from the dependency.

Typical object with a struct dependency:

// Object that relies on a struct
type ObjectUnderTestBefore struct {
    db *sql.DB
}

func (o *ObjectUnderTestBefore) Delete() error {
    o.db.Exec("DELETE FROM sometable")
}

Apply Dependency Inversion Principle (with implicit interface)

// subset of sql.DB which defines our "requirements"
type dbExec interface {
    Exec(query string, args ...interface{}) (sql.Result, error)
}

// Same object with it's requirement defined as an local interface
type ObjectUnderTestWithDIP struct {
    // *sql.DB will implicitly implement this interface
    db dbExec
}

func (o *ObjectUnderTestWithDIP) Delete() error {
    o.db.Exec("DELETE FROM sometable")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!