Skip to content

Instantly share code, notes, and snippets.

@sknuell
Last active February 10, 2021 22:22
Show Gist options
  • Save sknuell/023f9e268938d258cbf159dedaca5ad1 to your computer and use it in GitHub Desktop.
Save sknuell/023f9e268938d258cbf159dedaca5ad1 to your computer and use it in GitHub Desktop.
Mocking native PHP functions (date(), time() and shell_exec) for PHPUnit using php-mock/php-mock and php-mock/php-mock-phpunit
<?php
namespace Foo\Bar;
use phpmock\MockBuilder;
use phpmock\phpunit\PHPMock;
use PHPUnit_Framework_TestCase;
class Baz
{
/**
* @return string
*/
public function getDate(): string
{
return date('Y-m-d H:i:s');
}
/**
* @return int
*/
public function getTime(): int
{
return time();
}
/**
* @return string
*/
public function exec(): string
{
return shell_exec('cmd.sh');
}
}
class BazTest extends PHPUnit_Framework_TestCase
{
use PHPMock;
/**
* @var Baz
*/
private $baz;
/**
* Mocking date() and time() methods for _all_ test cases
*/
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
$builder = new MockBuilder();
$builder->setNamespace(__NAMESPACE__);
$builder->setName('date')
->setFunction(
function() {
return '2016-12-30 01:00:00';
}
);
$dateMock = $builder->build();
$dateMock->enable();
$builder->setName('time')
->setFunction(
function() {
return strtotime('2016-12-30 01:00:00');
}
);
$timeMock = $builder->build();
$timeMock->enable();
}
protected function setUp()
{
parent::setUp();
$this->baz = new Baz();
}
public function testGetDate()
{
$this->assertSame('2016-12-30 01:00:00', $this->baz->getDate());
}
public function testGetTime()
{
$this->assertSame(strtotime('2016-12-30 01:00:00'), $this->baz->getTime());
}
public function testExec()
{
// mocking shell_exec for selected test case using getFunctionsMock()
$mock = $this->getFunctionMock(__NAMESPACE__, 'shell_exec');
$mock->expects($this->once())->with('cmd.sh')->willReturn('output');
$this->assertSame('output', $this->baz->exec());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment