Wednesday, May 21, 2008

I Mock PHPUnit

I need to write PHPUnit tests for an OpenSocial class I am implementing in PHP and I am new to PHPUnit. The class required another class, a security token as input and I did not want to create a real token for my test. To my surprise, I discovered that PHPUnit has the ability to create Mock Objects built in. It was so easy to do I felt compelled to post this example which I dug up here.

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: