monkey

package module
v0.0.0-...-2942abf Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2025 License: MIT Imports: 5 Imported by: 0

README

Monkey - Gomonkey Generic

Go Reference Go Report Card Go Coverage Mentioned in Awesome Go

  • Monkey is a generic implementation of the gomonkey.
  • Monkey can be used in testing for stubbing.
  • Very easy to use: only 3 function in all.

Usage:

Patch a function:

	p := Func(nil, fnFoo, func() string { return "bar" })
	defer p.Reset()

	if fnFoo() != "bar" {
		t.Error("patch failed")
	}

You can also patch global variables and methods with Var and Method. Check the tests for example.

Notes

  • TL;DR: Be sure to add flag -gcflags=-l(below go1.10) or -gcflags=all=-l(go1.10 and above) in testing like go test -gcflags=all=-l -v
    • gomonkey fails to patch a function or a member method if inlining is enabled, please running your tests with inlining disabled by adding the command line argument that is -gcflags=-l(below go1.10) or -gcflags=all=-l(go1.10 and above).
  • A panic may happen when a goroutine is patching a function or a member method that is visited by another goroutine at the same time. That is to say, gomonkey is not threadsafe. Do not call t.Parallel in your tests.

Improvements Compared to the Original

  • Generic implementation instead of interface{} to provide type checks especially for functions/methods, which also benefits the code completion a lot.
  • Only 3 functions to achieve all benefits from gomonkey.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Func

func Func[Fn any](patches *gomonkey.Patches, target Fn, replacement Fn) *gomonkey.Patches

Func applies a function patch.

func Method

func Method[Receiver any, Fn any](patches *gomonkey.Patches, receiver Receiver, method Fn, replacement Fn) *gomonkey.Patches

Method applies a method patch.

func NewPatches

func NewPatches() *gomonkey.Patches

NewPatches returns a new Patches. Be sure to call `defer Patches.Reset()` on every `Patches`.

func Var

func Var[Var any](patches *gomonkey.Patches, target *Var, replacement Var) *gomonkey.Patches

Var applies a variable patch.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL