mock_objects_documentation.html.svn-base
来自「PHP 知识管理系统(基于树结构的知识管理系统), 英文原版的PHP源码。」· SVN-BASE 代码 · 共 758 行 · 第 1/3 页
SVN-BASE
758 行
Luckily the mocks have a filter system...<pre><strong>$config = &new MockConfiguration();$config->setReturnValue('getValue', 'primary', array('db_host'));$config->setReturnValue('getValue', 'admin', array('db_user'));$config->setReturnValue('getValue', 'secret', array('db_password'));</strong></pre> The extra parameter is a list of arguments to attempt to match. In this case we are trying to match only one argument which is the look up key. Now when the mock object has the <span class="new_code">getValue()</span> method invoked like this...<pre>$config->getValue('db_user')</pre> ...it will return "admin". It finds this by attempting to match the calling arguments to its list of returns one after another until a complete match is found. </p> <p> You can set a default argument argument like so...<pre><strong>$config->setReturnValue('getValue', false, array('*'));</strong></pre> This is not the same as setting the return value without any argument requirements like this...<pre><strong>$config->setReturnValue('getValue', false);</strong></pre> In the first case it will accept any single argument, but exactly one is required. In the second case any number of arguments will do and it acts as a catchall after all other matches. Note that if we add further single parameter options after the wildcard in the first case, they will be ignored as the wildcard will match first. With complex parameter lists the ordering could be important or else desired matches could be masked by earlier wildcard ones. Declare the most specific matches first if you are not sure. </p> <p> There are times when you want a specific object to be dished out by the mock rather than a copy. The PHP4 copy semantics force us to use a different method for this. You might be simulating a container for example...<pre>class Thing {}class Vector { function Vector() { } function get($index) { }}</pre> In this case you can set a reference into the mock's return list...<pre>$thing = &new Thing();<strong>$vector = &new MockVector();$vector->setReturnReference('get', $thing, array(12));</strong></pre> With this arrangement you know that every time <span class="new_code">$vector->get(12)</span> is called it will return the same <span class="new_code">$thing</span> each time. This is compatible with PHP5 as well. </p> <p> These three factors, timing, parameters and whether to copy, can be combined orthogonally. For example...<pre>$complex = &new MockComplexThing();$stuff = &new Stuff();<strong>$complex->setReturnReferenceAt(3, 'get', $stuff, array('*', 1));</strong></pre> This will return the <span class="new_code">$stuff</span> only on the third call and only if two parameters were set the second of which must be the integer 1. That should cover most simple prototyping situations. </p> <p> A final tricky case is one object creating another, known as a factory pattern. Suppose that on a successful query to our imaginary database, a result set is returned as an iterator with each call to <span class="new_code">next()</span> giving one row until false. This sounds like a simulation nightmare, but in fact it can all be mocked using the mechanics above. </p> <p> Here's how...<pre>Mock::generate('DatabaseConnection');Mock::generate('ResultIterator');class DatabaseTest extends UnitTestCase { function testUserFinder() {<strong> $result = &new MockResultIterator(); $result->setReturnValue('next', false); $result->setReturnValueAt(0, 'next', array(1, 'tom')); $result->setReturnValueAt(1, 'next', array(3, 'dick')); $result->setReturnValueAt(2, 'next', array(6, 'harry')); $connection = &new MockDatabaseConnection(); $connection->setReturnValue('query', false); $connection->setReturnReference( 'query', $result, array('select id, name from users'));</strong> $finder = &new UserFinder($connection); $this->assertIdentical( $finder->findNames(), array('tom', 'dick', 'harry')); }}</pre> Now only if our <span class="new_code">$connection</span> is called with the correct <span class="new_code">query()</span> will the <span class="new_code">$result</span> be returned that is itself exhausted after the third call to <span class="new_code">next()</span>. This should be enough information for our <span class="new_code">UserFinder</span> class, the class actually being tested here, to come up with goods. A very precise test and not a real database in sight. </p> <p><a class="target" name="expectations"><h2>Mocks as critics</h2></a></p> <p> Although the server stubs approach insulates your tests from real world disruption, it is only half the benefit. You can have the class under test receiving the required messages, but is your new class sending correct ones? Testing this can get messy without a mock objects library. </p> <p> By way of example, suppose we have a <span class="new_code">SessionPool</span> class that we want to add logging to. Rather than grow the original class into something more complicated, we want to add this behaviour with a decorator (GOF). The <span class="new_code">SessionPool</span> code currently looks like this...<pre><strong>class SessionPool { function SessionPool() { ... } function &findSession($cookie) { ... } ...}class Session { ...}</strong></pre> While our logging code looks like this...<pre><strong>class Log { function Log() { ... } function message() { ... }}class LoggingSessionPool { function LoggingSessionPool(&$session_pool, &$log) { ... } function &findSession($cookie) { ... } ...}</strong></pre> Out of all of this, the only class we want to test here is the <span class="new_code">LoggingSessionPool</span>. In particular we would like to check that the <span class="new_code">findSession()</span> method is called with the correct session ID in the cookie and that it sent the message "Starting session $cookie" to the logger. </p> <p> Despite the fact that we are testing only a few lines of production code, here is what we would have to do in a conventional test case: <ol> <li>Create a log object.</li> <li>Set a directory to place the log file.</li> <li>Set the directory permissions so we can write the log.</li> <li>Create a <span class="new_code">SessionPool</span> object.</li> <li>Hand start a session, which probably does lot's of things.</li> <li>Invoke <span class="new_code">findSession()</span>.</li> <li>Read the new Session ID (hope there is an accessor!).</li> <li>Raise a test assertion to confirm that the ID matches the cookie.</li> <li>Read the last line of the log file.</li> <li>Pattern match out the extra logging timestamps, etc.</li> <li>Assert that the session message is contained in the text.</li> </ol> It is hardly surprising that developers hate writing tests when they are this much drudgery. To make things worse, every time the logging format changes or the method of creating new sessions changes, we have to rewrite parts of this test even though this test does not officially test those parts of the system. We are creating headaches for the writers of these other classes. </p> <p> Instead, here is the complete test method using mock object magic...<pre>Mock::generate('Session');Mock::generate('SessionPool');Mock::generate('Log');class LoggingSessionPoolTest extends UnitTestCase { ... function testFindSessionLogging() {<strong> $session = &new MockSession(); $pool = &new MockSessionPool(); $pool->setReturnReference('findSession', $session); $pool->expectOnce('findSession', array('abc')); $log = &new MockLog(); $log->expectOnce('message', array('Starting session abc')); $logging_pool = &new LoggingSessionPool($pool, $log); $this->assertReference($logging_pool->findSession('abc'), $session);</strong> }}</pre> We start by creating a dummy session.
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?