Skip to content

Instantly share code, notes, and snippets.

@nfx
Created July 18, 2012 22:54
Show Gist options
  • Save nfx/3139512 to your computer and use it in GitHub Desktop.
Save nfx/3139512 to your computer and use it in GitHub Desktop.
Mockoko - yet another PHPUnit mocking shortcut
<?php
/**
* Yet another PHPUnit wrapper for mocking
*
* To enable, just add the following line in your base testcase:
*
* Mockoko::getInstance()->setTestCase($this);
*
* To use, just make your mocks as
*
* mock('Symfony\Component\Security\Core\SecurityContext', array(
* 'getToken' => mock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface', array(
* 'getUser' => new User()
* ))
* ));
*/
class Mockoko
{
/** @var Mockoko */
static private $instance;
/** @var \PHPUnit_Framework_TestCase */
private $testCase;
/** @return Mockoko */
static public function getInstance()
{
return empty(self::$instance)
? self::$instance = new static()
: self::$instance;
}
public function setTestCase(\PHPUnit_Framework_TestCase $tc)
{
$this->testCase = $tc;
}
public function mock($className, array $methodStubs)
{
$mock = $this->testCase->getMock($className);
foreach ($methodStubs as $methodName => $returnValue) {
$mock->expects($this->testCase->any())->method($methodName)
->will($this->testCase->returnValue($returnValue));
}
return $mock;
}
}
function mock($className, array $methodStubs)
{
return Mockoko::getInstance()->mock($className, $methodStubs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment