Monkey patching in Go unit tests with gomonkey, just disable inlining first

AI-generated summary of reporting by GitHub Opensource Projects. Read the original for the full story.

Why it matters

Go developers can now monkey-patch functions like time.Now in tests without refactoring to interfaces, but only if they remember to disable inlining.

Read this as

gomonkey is a free, open-source testing tool for the Go programming language. It lets developers temporarily swap out a piece of a program, say, a clock function, with a fake version during tests, something normally impossible in compiled languages. The catch is that a compiler shortcut called inlining must be turned off, or the swap silently fails. It is useful for developers maintaining older, hard-to-test code.

The gomonkey library (v3) lets Go teams patch functions in unit tests without refactoring legacy code to interfaces, potentially saving hours per dependency untangled. The trade-off is real risk: patches silently fail unless tests compile with -gcflags=-l, and runtime code modification can panic if the target runs on another goroutine. It is a tactical tool for deadline-pressed teams, not an idiomatic replacement for dependency injection.

gomonkey v3 monkey-patches Go functions by overwriting the target's machine-code entry point with a jump instruction to a replacement, working on amd64 and arm64. Inlined functions have no entry point, so patches require //go:noinline or compiling tests with -gcflags=-l, or they silently no-op. It supports patching package-level functions like time.Now, methods, call-count and argument verification. Limitations: undefined behavior if targets execute concurrently, test-only use recommended.

Read the original

This summary exists to save you time, not to replace the source.

Key terms

gomonkey Go Python Ruby time.Now os.Getenv

Was this summary useful?

One click, anonymous. It tells us which summaries to re-run.

Related reading