Skip to content

Instantly share code, notes, and snippets.

@mnapoli
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnapoli/e7f41f41d77ff0821881 to your computer and use it in GitHub Desktop.
Save mnapoli/e7f41f41d77ff0821881 to your computer and use it in GitHub Desktop.
PHPUnit extension
<?php
$mock = SimpleMock::mock('My\Class', array(
'getBar' => 'hello',
'doSomething' => function ($param) {
echo 'foo';
},
));
// Same as
$mock = $this->getMock('My\Class', array(), array(), '', false);
$mock->expect($this->any())
->method('getBar')
->willReturn('hello');
$mock->expect($this->any())
->method('doSomething')
->willReturnCallback(function ($param) {
echo 'foo';
});
// Other example:
$mock = SimpleMock::mock('DbHelper', array(
'getAdapter' => SimpleMock::mock('Db', array(
'fetchAll' => array(/* ... */),
)),
));
// Can still be used in case we want to perform assertions
$mock = SimpleMock::mock('My\Class', array(
'getDependency' => $someOtherMock,
));
$mock->expect($this->once())
->method('doSomething')
->with('foo', 'bar')
->willReturn('Hello world!');
<?php
class SimpleMock
{
public static function mock($classname, array $methods = array())
{
$mockGenerator = new PHPUnit_Framework_MockObject_Generator();
$mock = $mockGenerator->getMock(
$classname,
array(),
array(),
'',
false
);
foreach ($methods as $method => $return) {
$methodAssertion = $mock->expect($this->any())
->method($method);
if (is_callable($methodAssertion)) {
$methodAssertion->willReturnCallback($return);
} else {
$methodAssertion->willReturn($return);
}
}
return $mock;
}
private function any()
{
return new PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment