[Go] Set a mock method's return value with GoMock

Created on November 30, 2026

You can use GoMock's Return method to define what a mock method returns for a given call. In a Go module, save this interface as calculator.go.

package calculator

type Calculator interface {
    AddNumbers(a, b int) int
}

Install GoMock and generate the mock from that interface.

go get go.uber.org/mock@v0.6.0
go run go.uber.org/mock/mockgen@v0.6.0 -source=calculator.go \
    -destination=calculator_mock_test.go -package=calculator

Save this test as calculator_test.go.

package calculator

import (
    "testing"

    "go.uber.org/mock/gomock"
)

func TestAddNumbers(t *testing.T) {
    ctrl := gomock.NewController(t)
    mock := NewMockCalculator(ctrl)
    mock.EXPECT().AddNumbers(gomock.Any(), gomock.Any()).Return(10)

    if got := mock.AddNumbers(3, 5); got != 10 {
        t.Fatalf("AddNumbers(3, 5) = %d, want 10", got)
    }
}

gomock.Any() matches any value for either argument. Return(10) gives the mock a fixed return value, so go test passes when the mock returns 10 for the call with 3 and 5.

Reference

Go