Mock for date('m') function php (Zend)

Viewed 61

How can I mock for PHP default functions like date and time?

I tried,

$builder = $this->getMockBuilder(__NAMESPACE__)->getMock();
$builder->expects($this->once())->method('date')->with('m')->willReturn('test');

It's giving me the error,

Trying to configure method "date" which cannot be configured because it does not exist, has not been specified, is final, or is static

2 Answers

To mock PHP functions, you could use this package: https://packagist.org/packages/hjerichen/prophecy-php

This is a simple example for a test method in a PHPUnit TestCase:

$php = $this->prophesizePHP(__NAMESPACE__);
$php->date('Y', 1234)->willReturn('1970');
$php->date('Y', 1234000)->willReturn('1971');
$php->reveal();

Disclaimer: I wrote this library

If you can install php extensions on your system, then give https://github.com/slope-it/clock-mock a try.

By using ClockMock::freeze and ClockMock::reset you can move the internal php clock to any point in time. The cool thing is that it works with zero modifications to your production code as it transparently mocks php datetime objects and time-related functions.

Related