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(){
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

No comments: