Monkey Patching in Go
In the Go programming language, mocking can be challenging when dealing with code that is not structured around interfaces. When structs are directly interconnected and dependency injection is not present, it hinders the ability to effectively test and benchmark without modifying the underlying code.
One technique that may come to mind from scripting languages like Python is monkey patching, where objects can be modified at runtime. While Go does not have an equivalent mechanism for direct object modification, there are alternative approaches to achieve similar results.
One common strategy is to create your own interface as a wrapper around the structs you wish to mock. This allows you to implement the desired behavior in the interface methods, while preserving the original functionality in the underlying struct. For instance:
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() }
By implementing MyInterface, you can now create mock implementations for your tests:
// MockMyInterface implements MyInterface for testing purposes type MockMyInterface struct { mockedDoSomethingError error mockedDoSomethingElseResult []int } func (m *MockMyInterface) DoSomething(i int) error { return m.mockedDoSomethingError } func (m *MockMyInterface) DoSomethingElse() ([]int, error) { return m.mockedDoSomethingElseResult, nil }
Another approach, suggested by @elithrar in the comments, is to embed the type you wish to mock within your own struct. This allows you to selectively mock only the methods that require it:
type Concrete struct { *somepackage.Client }
By embedding Client, you can directly call methods like DoSomethingNotNeedingMocking without adding them to the interface or creating mocks for them.
These techniques provide viable alternatives to monkey patching for testing and benchmarking code that is not structured around interfaces.
The above is the detailed content of How Can I Achieve the Effect of Monkey Patching in Go for Testing and Benchmarking?. For more information, please follow other related articles on the PHP Chinese website!