Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mock: add assertion for minimum number of method/function invocations #1595

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

shalinlk
Copy link

@shalinlk shalinlk commented May 3, 2024

Summary

Method for asserting minimum number of invocations made to a method.

Changes

Added assertion method named AssertMinNumberOfCalls which takes expected minimum number of calls along with the method name for assertion. Assertion fails if specified minimum number of invocations are not made to the method.

Motivation

There are cases where exact number of invocations of a method cannot be predetermined accurately. Eg, number of network calls made by a retry logic which is governed by time out and time delay. 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

Example usage

mockClient.AssertMinNumberOfCalls(t, "ModifyRule", 6)

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
@dolmen dolmen changed the title Assertion for minimum number of method/function invocations mock: add assertion for minimum number of method/function invocations May 16, 2024
@dolmen dolmen added enhancement pkg-mock Any issues related to Mock labels May 16, 2024
@brackendawson
Copy link
Collaborator

How does this behave if the method has multiple calls? The doc on the new method doesn't say.

I would prefer not to expand the API with more methids like this. I don't think AssertNumberOfCalls should have been added because it has the same problem. It's better to set the expectations up front and use AssertExpectations. This is how you can cleanly assert a minimum number of calls up front:

func TestMyClassDoThings(t *testing.T) {
	mockThing := &myMockThing{}
	mockThing.Test(t)
	defer mockThing.AssertExpectations(t)
	mockThing.On("ModifyRule").Return().Times(6)
	mockThing.On("ModifyRule").Return().Maybe()
	
	c := MyClass{
		Thing: mockThing,
	}
	c.DoThings()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement pkg-mock Any issues related to Mock
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants