From 2013c06d0ffdc2c79dc0fea1d153585ef238646e Mon Sep 17 00:00:00 2001 From: Saauf Date: Sat, 5 Sep 2026 18:30:15 +0200 Subject: [PATCH] mock: avoid copying call history in AssertNumberOfCalls --- mock/mock.go | 4 ++-- mock/mock_test.go | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/mock/mock.go b/mock/mock.go index 746151e1b..cdb665a84 100644 --- a/mock/mock.go +++ b/mock/mock.go @@ -666,8 +666,8 @@ func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls m.mutex.Lock() defer m.mutex.Unlock() var actualCalls int - for _, call := range m.calls() { - if call.Method == methodName { + for i := range m.Calls { + if m.Calls[i].Method == methodName { actualCalls++ } } diff --git a/mock/mock_test.go b/mock/mock_test.go index c30f526c4..92c1595d5 100644 --- a/mock/mock_test.go +++ b/mock/mock_test.go @@ -1744,6 +1744,23 @@ func Test_Mock_AssertNumberOfCalls(t *testing.T) { } +func Benchmark_Mock_AssertNumberOfCalls(b *testing.B) { + b.ReportAllocs() + + m := new(Mock) + m.On("BenchmarkMethod", 1).Return() + for i := 0; i < 100; i++ { + m.MethodCalled("BenchmarkMethod", 1) + } + + t := new(testing.T) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.AssertNumberOfCalls(t, "BenchmarkMethod", 100) + } +} + func Test_Mock_AssertCalled(t *testing.T) { t.Parallel()