xp-framework/rfc — Issue #219: Mocking Library
Author: iigorr
Created: 2011-11-17 16:15:03+00:00
State: open
Labels: discussion, framework, implemented

Scope of Change
---------------
A mocking framework will be added to the unittest API.

Rationale
---------
Easily mock interfaces and verify expected behaviour similar to EasyMock (Java),
Rhino Mocks (.Net) and many other mocking frameworks.

Functionality
-------------
A new namespace 'unittest.mock' is introduced containing everything that enables
mock functionallity. A new class 'unittest.mock.Mockery' provides a method
'createMock($interfaceName)'. This method generates a mock object which
implements the required interface and provides methods for defining and
verifying expected behaviour.

The mocking framework should follow the record/replay/verfiy paradigm as
described here http://martinfowler.com/articles/mocksArentStubs.html or here
http://ayende.com/Blog/archive/2007/12/26/The-RecordReplayVerify-model.aspx

In the first step, the mocking of return values will be implemented. Later,
following features may follow:
* Method argument matching
* Behaviour verification
* Execution order verification
* Strick mocks (unsatisfied expectation)
* Rewinding the replay state
* Switching back to record after replay started

Example (Return values):
Consider an interface like the following.
interface Session {
... //many methods
public function getId();
}

Now we have the following method which we would like to unittest:

public function foo(Session $session) {
$this->bar(); //do something else
$this->baz($session->getId()); //do something with the session id
}

To cover this method it is irrelevant how the session object looks like.
Only the session id is of interest. Thus it would be nice if one could quickly
create a mock object for this:

[@test]
public function fooIsCalledWithoutException() {
$sessionMock= $mockery->createMock('Session');
$sessionMock->getId()->return(7); //return 7 if getId is called
$sessionMock->replay();

$this->sut->foo($sessionMock);
}

Security considerations
-----------------------
n/a

Speed impact
------------
Unittests will run faster if simple mocks are used instead of complex
instantiation of dependency objects.

Dependencies
------------
XP Framework

Related documents
-----------------

Comments
--------