Monkey Patching in Go: A Solution for Unchangeable Code Bases
Working with code bases that are not programmed to interfaces and heavily interconnected can present challenges for testing and benchmarking. In such scenarios, traditional mocking techniques may not be applicable. However, there is a strategy in Go that can help: monkey patching.
When faced with a similar situation, the suggested approach involves creating a custom interface as a wrapper around the unmodifiable code. This allows you to mock specific methods in tests while leaving the original code intact.
To illustrate, consider the following 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() }
In this scenario, Concrete is the code you cannot modify. By creating the MyInterface interface and embedding the original Concrete struct, you gain the flexibility to mock its methods in tests:
// Replace the embedded type with a mock in tests type MockConcrete struct { MyInterface } func (m *MockConcrete) DoSomething(i int) error { // Implement custom logic for mocking DoSomething }
This approach provides a way to test specific functionality without modifying the underlying code.
Alternatively, as suggested in the comments, you can also embed the desired type directly instead of creating a separate interface. This allows you to selectively mock only the methods you need:
type Concrete struct { *somepackage.Client }
This strategy retains the ability to access non-mocked methods directly on the embedded type, providing greater flexibility in testing.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3