Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

More flexible assertions for mock calls

But still providing test confidence

Joel Clermont
Joel Clermont
2024-11-15

From our daily Laravel tips email. Get the next one in your inbox.

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 your code? Explore our code review options.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.