From c1a498eca9ede8ecfb7f00deb606d10772907ade Mon Sep 17 00:00:00 2001 From: shalinlk Date: Fri, 3 May 2024 14:48:08 +0530 Subject: [PATCH] Assertion for minimum number of method/function calls There are cases where exact number of calls that will be made inside a method cannot be predtermined accurately. Eg, number of network calls made by a retry logic which is governed by a time out. Number of calls made in such cases will depend on time of previous call and time out of governing context. Hence ability to ensure a minimum threshold is required --- mock/mock.go | 16 ++++++++++++++++ mock/mock_test.go | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/mock/mock.go b/mock/mock.go index d5eb1ef55..fb563cfe4 100644 --- a/mock/mock.go +++ b/mock/mock.go @@ -648,6 +648,22 @@ func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) } +// AssertMinNumberOfCalls asserts that the method was called at-least expectedMinCalls times. +func (m *Mock) AssertMinNumberOfCalls(t TestingT, methodName string, expectedMinCalls int) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + var actualCalls int + for _, call := range m.calls() { + if call.Method == methodName { + actualCalls++ + } + } + return assert.LessOrEqual(t, expectedMinCalls, actualCalls, fmt.Sprintf("Actual number of calls (%d) does not satisfy the minimum expected number of calls (%d).", actualCalls, expectedMinCalls)) +} + // AssertCalled asserts that the method was called. // It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { diff --git a/mock/mock_test.go b/mock/mock_test.go index b80a8a75b..9e75a5301 100644 --- a/mock/mock_test.go +++ b/mock/mock_test.go @@ -1536,6 +1536,22 @@ func Test_Mock_AssertNumberOfCalls(t *testing.T) { } +func Test_Mock_AssertMinNumberOfCalls(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertMinNumberOfCalls", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertMinNumberOfCalls", 1)) + assert.True(t, mockedService.AssertMinNumberOfCalls(t, "Test_Mock_AssertMinNumberOfCalls", 1)) + + mockedService.Called(1, 2, 3) + assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertMinNumberOfCalls", 2)) + assert.True(t, mockedService.AssertMinNumberOfCalls(t, "Test_Mock_AssertMinNumberOfCalls", 1)) + assert.True(t, mockedService.AssertMinNumberOfCalls(t, "Test_Mock_AssertMinNumberOfCalls", 2)) +} + func Test_Mock_AssertCalled(t *testing.T) { var mockedService = new(TestExampleImplementation)