I have talked about the importance of specifying how many times a method should be called in a mock assertion.
But sometimes it is hard to be precise about the number of times a mock is called.
For example, I was mocking a feature flag helper and I had a scenario where I wanted to ensure it was called at least once, but I didn't care if it was called more than that.
I could have specified the exact current number of calls, but because of how the helper was built, I knew that would lead to a brittle test I'd just have to change in the future.
There is a better way to do this. Mockery allows us to specify a minimum number of calls:
$featureMock = $this->mock(ThirdPartyService::class);
$featureMock->shouldReceive('active')
->with(FeatureFlag::SOME_FLAG_NAME)
->atLeast()->once()
->andReturnTrue();
// rest of test execution here
This way I know it's called "at least" once, but it doesn't fail if it's two or three times.
As you might expect, there's also an atMost()
method if you need that logic instead.
Here to help,
Joel
P.S. Would you like an expert opinion on how good your tests are? I can help with that.