This post originated from an RSS feed registered with PHP Buzz
by Sebastian Bergmann.
Original Post: Mock Objects in PHPUnit
Feed Title: Sebastian Bergmann
Feed URL: http://sebastian-bergmann.de/
Feed Description: Geek by nature, PHP by choice.
While I am preparing the PHPUNIT_2_3 CVS branch for a release of PHPUnit 2.3.0 alongside PHP 5.1.0, I recently started working on support for Mock Objects in PHPUnit.
Suppose you have the following class Foo:
<?php
class Foo {
public function bar() {
}
}?>
You can now write a test case that checks whether or not the bar() gets called on an object of the Foo class:
<?php
require_once 'PHPUnit2/Framework/TestCase.php';
class FooTest extends PHPUnit2_Framework_TestCase {
public function testBarGetsCalled() {
$mock = $this->getMockObject('Foo');
$mock->__expectAtLeastOnce('bar');
$mock->bar();
$mock->__tally();
}
}?>
The getMockObject('Foo') call generates a class MockFoo (the Mock Object class for Foo) that extends from Foo and the signatures of all public methods are copied from Foo to MockFoo. In addition, a couple of MockObjects API methods are added to the MockFoo class:
These methods can be used to set up expectations and return values for the stubbed-out methods of the Mock Object.
The work on the Code Generator that generates the code for a Mock Object class is complete and I started to work on the PHPUnit2_Extensions_MockObjects_CallMap class today. The next step will be to tie the Mock Objects functionality into the PHPUnit framework.