Golang Monkey Patching for Unmodifiable Code
In Go, the absence of runtime object modification poses a challenge for testing heavily interconnected code that lacks dependency injection or interface programming. To work around this limitation, consider using the following approach:
Creating a Mocking Wrapper Interface
Define your own interface that wraps the original structs. For instance:
type MyInterface interface { DoSomething(i int) error DoSomethingElse() ([]int, error) }
Using an Adapter Struct
Implement the wrapper interface in a new struct that adapts the original struct's implementation:
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() }
Testing with the Wrapper
You can now mock the Concrete struct in unit tests because it adheres to an interface:
// Mock Concrete mock := &MockMyInterface{} c := Concrete{mock} // Call mock method err := c.DoSomething(10)
Embedding the Original Type
As suggested by @elithrar, you can also embed the original type to selectively mock only necessary methods:
type Concrete struct { *somepackage.Client }
In this case, you can still access the original implementation of methods that don't need mocking:
c := Concrete{&somepackage.Client{}} c.DoSomethingNotNeedingMocking() // Calls the original implementation
The above is the detailed content of How Can I Mock Unmodifiable Go Code for Testing?. For more information, please follow other related articles on the PHP Chinese website!