When a function accepts a callback parameter, how do you verify in PHPUnit that the callback was actually called, with the correct arguments and the right number of times?
What’s Wrong with the Naive Approach
Given this function:
| |
The most intuitive approach is to put assertions inside the closure:
| |
This verifies the argument, but if executeCallback never calls $callback, the test still passes because the assertion is never executed.
Using Mockery::spy to Verify Closures
According to this PR, Mockery supports spying on closures directly:
| |
| |
If the callback is never called, shouldHaveBeenCalled() will fail the test. You can also verify the call count:
| |
The test structure follows the 3A pattern (Arrange-Act-Assert), which is more readable than embedding assertions inside the closure – and correctly catches the case where the callback is never called at all.
