[Go] Check how many times a mock method was called with Testify

Created on November 29, 2026

You can use AssertNumberOfCalls from testify/mock to check how many times a mock method was called.

This test creates a mock for the AddNumbers method and verifies that it was called twice.

package main

import (
    "testing"

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

type Calculator struct {
    mock.Mock
}

func (c *Calculator) AddNumbers(a int, b int) int {
    args := c.Called(a, b)
    return args.Int(0)
}

func TestAddNumbers(t *testing.T) {
    calculator := new(Calculator)
    calculator.On("AddNumbers", 3, 5).Return(8)

    calculator.AddNumbers(3, 5)
    calculator.AddNumbers(3, 5)

    calculator.AssertNumberOfCalls(t, "AddNumbers", 2)
}
  • Calculator embeds mock.Mock. Its AddNumbers method calls c.Called(a, b) to record the call and look up the configured return value.
  • On("AddNumbers", 3, 5).Return(8) configures the mock to return 8 when called with 3 and 5.
  • After calling AddNumbers twice, AssertNumberOfCalls checks the total for the method name.

Reference

Go