Golang monkey patching

后端 未结 3 1584
悲哀的现实
悲哀的现实 2020-12-10 13:59

I understand that if go code is structured such that it\'s programmed to interfaces, it\'s trivial to mock; however, I\'m working with a code base that I cannot change (that

相关标签:
3条回答
  • 2020-12-10 14:12

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

    0 讨论(0)
  • 2020-12-10 14:25

    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")
    }
    
    0 讨论(0)
  • 2020-12-10 14:26

    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.

    0 讨论(0)
提交回复
热议问题