Using xgo for Monkey Patching, Mocking, Tracing, and Incremental Coverage in Go
This article introduces the xgo tool for Go, explains its cross‑platform monkey‑patching capabilities, demonstrates how to write unit tests with mock.Patch, shows installation, usage of Trap, Trace, and incremental coverage features, and evaluates its advantages and drawbacks for backend development.
The author, a Go developer with ten years of experience, revisits the concept of monkey patching and presents xgo , a powerful Go testing toolkit that provides Trap, Mock, Trace, and incremental coverage functionalities.
xgo supports all major operating systems (Linux, Windows, macOS) and architectures (x86, x86_64, arm64), making it a truly cross‑platform solution for Go projects.
An example HTTP service written in Go is shown, exposing POST /users and GET /users/:id endpoints. The article then demonstrates how to install xgo via go install github.com/xhd2015/xgo/cmd/xgo@latest and verify the version.
For unit testing, the author focuses on the (*UserHandler).CreateUser and (*UserHandler).GetUser methods. By using mock.Patch from xgo , the underlying *gorm.DB methods are monkey‑patched with custom implementations, allowing tests to run without touching the original database logic. Test execution is performed with xgo test -v -run TestUserHandler_CreateUser and similar commands.
The article also covers the Trap feature, which intercepts Go function calls, and provides a minimal example where a pre‑interceptor prints messages before functions A and B are executed. Running the program with xgo run shows the interceptor output.
Trace functionality is introduced next; adding the --strace flag to xgo test generates a JSON trace file that can be visualized with xgo tool trace , offering a graphical view of call stacks and error locations.
Incremental coverage is explained as a way to compute test coverage only for code changes tracked by Git. The command xgo test -v -coverpkg . -coverprofile cover.out produces a coverage report, which can be served locally via xgo tool coverage serve cover.out to view both incremental and full coverage.
In the summary, the author lists the strengths of xgo —excellent cross‑platform support, concurrency safety, no need for explicit reset after patching, and simple command substitution—and its weaknesses, such as the requirement to install xgo , limited Go version compatibility, slower and buggy Trace, and lack of a --help flag.
References to the xgo source code, related blog posts, and a Go Night Reading session are provided for readers who wish to explore the tool further.
Go Programming World
Mobile version of tech blog https://jianghushinian.cn/, covering Golang, Docker, Kubernetes and beyond.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.