package stub

import "go.abhg.dev/testing/stub"

Package stub provides helper functions to replace global variables for testing, and restore them afterwards.

Index

Functions

func Func

func Func(fnptr any, rets ...any) (restore func())

Func replaces the value of a function pointer with a function that returns the provided values. It returns a function that restores the original function. If the function has multiple return values, pass them all.

Idiomatic usage will typically look like this:

func TestSomething(t *testing.T) {
	defer stub.StubFunc(&globalFunc, 42)()

	globalFunc() // returns 42
	// ...
}

If the test has subtests that use t.Parallel, use t.Cleanup instead of defer:

func TestSomething(t *testing.T) {
	t.Cleanup(stub.StubFunc(&globalFunc, 42))

	t.Run("subtest", func(t *testing.T) {
		t.Parallel()

		globalFunc() // returns 42
		// ...
	})
}

func Value

func Value[T any](ptr *T, value T) (restore func())

Value replaces the value of a pointer with a new value, and returns a function that restores the original value.

Idiomatic usage will typically look like this:

func TestSomething(t *testing.T) {
	defer stub.Value(&globalVar, newValue)()

	// ...
}

If the test has subtests that use t.Parallel, use t.Cleanup instead of defer:

func TestSomething(t *testing.T) {
	t.Cleanup(stub.Value(&globalVar, newValue))

	t.Run("subtest", func(t *testing.T) {
		t.Parallel()

		// ...
	})
}