Last active
August 29, 2015 14:09
-
-
Save mnapoli/e7f41f41d77ff0821881 to your computer and use it in GitHub Desktop.
PHPUnit extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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!'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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