Skip to content

Instantly share code, notes, and snippets.

@aikar
Created Sep 27, 2011
Embed
What would you like to do?
<?php
require("phpmock.php");
class foo extends PHPUnit_PHPMock {
function testbar() {
$php = self::getMock('php', array('time'));
$php->expects(self::once())->method('time')->will(self::returnValue(32));
echo time();
}
}
<?php
/**
* Enables mocking of functions (internal & user)
*
* $oPHP = self::getMock('php, array('file_put_contents'));
* $oPHP->expects(self::once())
* ->method('file_put_contents')
* ->with('foo', 'bar')
* ->will(self::returnValue(true));
*
* file_put_contents('foo', 'bar');
*/
class php {
static protected $aOverloaded = array();
static protected $oInstance = null;
static public function getInstance() {
if (self::$oInstance == null) {
self::$oInstance = new self;
}
return self::$oInstance;
}
static public function setInstance($oInstance) {
self::$oInstance = $oInstance;
}
static public function _override($sMethod) {
$sOverload = <<<CODE
function $sMethod () {
\$aArgs = func_get_args();
\$aMethod = array(php::getInstance(), '$sMethod');
\$mReturn = call_user_func_array(\$aMethod, \$aArgs);
return \$mReturn;
}
CODE;
$sNew = "__php_$sMethod";
if (!function_exists($sNew)) {
rename_function($sMethod, $sNew);
eval ($sOverload);
self::$aOverloaded[] = $sMethod;
}
}
/**
* Restores all functions to original. Segfault on process end without this?
*/
function _restore() {
foreach(self::$aOverloaded as $sKey => $sFunction) {
rename_function($sFunction, uniqid($sFunction));
rename_function('__php_'.$sFunction, $sFunction);
}
self::$aOverloaded = array();
}
function __call($sMethod, $aArgs) {
return call_user_func_array('__php_' . $sMethod, $aArgs);
}
}
register_shutdown_function(function() {
php::_restore();
});
class PHPUnit_PHPMock extends PHPUnit_Framework_TestCase {
public function getMock($sClass, $aMethods) {
if ($sClass == 'php') {
php::_restore();
foreach($aMethods as $sMethod) {
php::_override($sMethod);
}
}
$oInstance = call_user_func_array(array('parent', 'getMock'), func_get_args());
if ($sClass == 'php') {
php::setInstance($oInstance);
}
return $oInstance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment