mock

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2025 License: Unlicense Imports: 0 Imported by: 0

Documentation

Overview

Package mock contains simple utilities for testing with mocks.

A Mock can be installed and restored. This package contains types and functions for creating and using such mocks.

The main idea is that instead of this

m1 := &mockWhatever{
	Foo: "bar",
}
m1.Install()
defer m1.Restore()

m2 := &mockAnother{
	Baz: "Quux",
}
m2.Install()
defer m2.Restore()

we can do this

mocks := mock.Group{
	&mockWhatever{
		Foo: "bar",
	},
	&mockAnother{
		Baz: "Quux",
	},
}
mocks.Install()
defer mocks.Restore()

or

func TestSomething(t *testing.T) {
	mock.UntilCleanup(t,
		&mockWhatever{
			Foo: "bar",
		},
		&mockAnother{
			Baz: "Quux",
		},
	)

	...
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Install

func Install(ms ...Mock)

Install installs each of the given Mocks.

func Restore

func Restore(ms ...Mock)

Restore restores each of the given Mocks. They are restored in reverse order, in case they have ordering dependencies.

func UntilCleanup

func UntilCleanup(t Cleanupper, ms ...Mock)

UntilCleanup installs the given mocks and tells t to restore them on Cleanup. Usually, t is a *testing.T.

Types

type Cleanupper

type Cleanupper interface {
	Cleanup(func())
}

A Cleanupper can be asked to call a cleanup function. The most common Cleanupper is *testing.T.

type Group

type Group []Mock

A Group allows a collection of Mocks to be treated as one.

func (Group) Install

func (g Group) Install()

Install installs each mock in g.

func (Group) Restore

func (g Group) Restore()

Restore restores each mock in g.

type Mock

type Mock interface {
	Install() // Install sets up the Mock for use in tests.
	Restore() // Restore undoes changes made by Install.
}

A Mock can be installed and restored.

func Set

func Set[T any](mockable *T, mock T) Mock

Set returns a Mock that sets *mockable to mock at Install, saving *mockable's original value. On Restore, *mockable is reset to its original value.

Jump to

Keyboard shortcuts

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