Skip to content

Templates

Mockery, in its essence, renders templates. This project provides a number of pre-curated templates that you can select with the template: config parameter.

Template Options

template: "testify"

testify templates generate powerful, testify-based mock objects. They allow you to create expectations using argument-to-return-value matching logic.

Go
package test

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestRequesterMock(t *testing.T) {
    m := NewMockRequester(t)
    m.EXPECT().Get("foo").Return("bar", nil).Once()
    retString, err := m.Get("foo")
    assert.NoError(t, err)
    assert.Equal(t, retString, "bar")
}

template: "matryer"

matryer templates draw from the mocks generated from the project at https://github.com/matryer/moq. This project was folded into mockery, and thus moq-style mocks can be natively generated from within mockery.

Mocks generated using this template allow you to define precise functions to be run. Example:

Go
func TestRequesterMoq(t *testing.T) {
    m := &MoqRequester{
        GetFunc: func(path string) (string, error) {
            fmt.Printf("Go path: %s\n", path)
            return path + "/foo", nil
        },
    }
    result, err := m.Get("/path")
    assert.NoError(t, err)
    assert.Equal(t, "/path/foo", result)
}

template: "file://

You may also provide mockery a path to your own file using the file:// protocol specifier. The string after file:// will be the relative or absolute path of your template.

The templates are rendered with the data as shown in the section below.

You can see examples of how the mockery project utilizes the template system to generate the different mock styles:

Template Data

Functions

Template files have both StringManipulationFuncs and TemplateMockFuncs available as functions.

Variables

The template is supplied with the template.Data struct. Some attributes return types such as template.MockData and template.Package which themselves contain methods that may also be called.