If I want to create a Mock Object for the class RingsideGadgetToken for example and it has a default (No argument constructor) all I had to do was this:
public function createMockToken(){
$uid_='100000';}
$api_key_='4333592132647f39255bb066151a2099';
$api_secret_='b37428ff3f4320a7af98b4eb84a4aa99';
$token=$this->getMock('RingsideGadgetToken');
$token->expects($this->any())->method('getAppId')->will($this->returnValue($api_key_));
$token->expects($this->any())->method('getOwnerId')->will($this->returnValue($uid_));
$token->expects($this->any())->method('getViewerId')->will($this->returnValue($uid_));
return $token;
And I had a fully functional mock RingsideGadgetToken. If I had wanted to I could have failed if a method was called more than once (expects($this->once())) or a specific number of times (expects($this->exactly(4))). Below is the complete example I found in Sebastian Bergmann's presentation referenced above which got me started:
require_once 'PHPUnit_Framework_TestCase';
class SubTest extends PHPUnit_Framework_TestCase
{
public function testStub()
{
$stub = $this->getMock('SomeClass'); $stub->expects($this->any())->method('doSomething')->will($this->returnValue('foo'));}
// Calling $stub->doSomething() will now return
// 'foo'
}
?>
Anyway, I was so pleasantly surprised, I thought it worth talking about. There is a great guide to PHPUnit I came across as well at http://www.phpunit.de/pocket_guide/index.en.php
No comments:
Post a Comment