php-mock/php-mock-mockery
Integrates php-mock with Mockery to mock PHP built-in functions in tests. Create namespaced function mocks with PHPMockery::mock() and set expectations/returns, then call Mockery::close(). Supports only unqualified calls; define early if needed.
composer require --dev php-mock/php-mock-mockery
use PHPMock\Mockery\PHPMock;
class MyTest extends TestCase
{
use PHPMock;
// ...
}
time()), using Mockery’s familiar syntax:
$timeMock = $this->getFunctionMock(__NAMESPACE__, 'time');
$timeMock->expects($this->once())->willReturn(1234567890);
First use case: Test a timestamp-dependent function (date('Y', time())) deterministically without relying on real time.getFunctionMock($namespace, $functionName) to get a Mockery-compatible mock for any PHP function, even internal ones like file_exists, rand, microtime.__NAMESPACE__) to avoid clobbering global functions and ensure isolation.expects($this->exactly(3)), andReturn(), andThrow() etc. exactly as you would for objects.setUp/tearDown or @before/@after annotations to isolate mocks per test:
protected function setUp(): void {
$this->getFunctionMock(__NAMESPACE__, 'time')->willReturn(0);
}
sleep, shuffle) to avoid delays or randomness:
$this->getFunctionMock(__NAMESPACE__, 'sleep')->andReturn(0); // skips delay
Tests\, but the code under test is in App\Services, pass App\Services::class or the string 'App\\Services' to getFunctionMock(). Using __NAMESPACE__ in a test trait may mislead you!App\time() won’t affect calls to time() in the global namespace. Always target the calling namespace.php-mock replaces internal functions by registering a runtime autoloader. This only works in CLI (CLI unit tests), not in web contexts. Always use in unit/integration tests, never in dev/staging app bootstrapping.namespace and that the mocked function is actually being called in the target namespace (e.g., date() calls use global time() unless namespaced).php-mock/php-mock-phpunit for trait-based mocks across multiple test suites, or use PHPMock::disableGlobalMock() to reset mocks between groups of tests.How can I help you explore Laravel packages today?