PageRenderTime 58ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/swiftmailer/test-suite/lib/simpletest/docs/source/en/mock_objects_tutorial.xml

https://bitbucket.org/cryofrost/portal
XML | 359 lines | 350 code | 8 blank | 1 comment | 0 complexity | 148be856f4e2c4069b1ce0a646381071 MD5 | raw file
Possible License(s): Apache-2.0, JSON, LGPL-2.1, LGPL-2.0, LGPL-3.0, BSD-3-Clause, BSD-2-Clause
  1. <?xml version="1.0"?>
  2. <!-- $Id: mock_objects_tutorial.xml 1687 2008-03-06 13:05:45Z pp11 $ -->
  3. <page title="Mock Objects" here="Using mock objects">
  4. <long_title>PHP unit testing tutorial - Using mock objects in PHP</long_title>
  5. <content>
  6. <section name="refactor" title="Refactoring the tests again">
  7. <p>
  8. Before more functionality is added there is some refactoring
  9. to do.
  10. We are going to do some timing tests and so the
  11. <code>TimeTestCase</code> class definitely needs
  12. its own file.
  13. Let&apos;s say <em>tests/time_test_case.php</em>...
  14. <php><![CDATA[
  15. <strong><?php
  16. if (! defined('SIMPLE_TEST')) {
  17. define('SIMPLE_TEST', 'simpletest/');
  18. }
  19. require_once(SIMPLE_TEST . 'unit_tester.php');
  20. class TimeTestCase extends UnitTestCase {
  21. function TimeTestCase($test_name = '') {
  22. $this->UnitTestCase($test_name);
  23. }
  24. function assertSameTime($time1, $time2, $message = '') {
  25. if (! $message) {
  26. $message = "Time [$time1] should match time [$time2]";
  27. }
  28. $this->assertTrue(
  29. ($time1 == $time2) || ($time1 + 1 == $time2),
  30. $message);
  31. }
  32. }
  33. ?></strong>
  34. ]]></php>
  35. We can then <code>require()</code> this file into
  36. the <em>all_tests.php</em> script.
  37. </p>
  38. </section>
  39. <section name="timestamp" title="Adding a timestamp to the Log">
  40. <p>
  41. I don&apos;t know quite what the format of the log message should
  42. be for the test, so to check for a timestamp we could do the
  43. simplest possible thing, which is to look for a sequence of digits.
  44. <php><![CDATA[
  45. <?php
  46. require_once('../classes/log.php');<strong>
  47. require_once('../classes/clock.php');
  48. class TestOfLogging extends TimeTestCase {
  49. function TestOfLogging() {
  50. $this->TimeTestCase('Log class test');
  51. }</strong>
  52. function setUp() {
  53. @unlink('../temp/test.log');
  54. }
  55. function tearDown() {
  56. @unlink('../temp/test.log');
  57. }
  58. function getFileLine($filename, $index) {
  59. $messages = file($filename);
  60. return $messages[$index];
  61. }
  62. function testCreatingNewFile() {
  63. ...
  64. }
  65. function testAppendingToFile() {
  66. ...
  67. }<strong>
  68. function testTimestamps() {
  69. $log = new Log('../temp/test.log');
  70. $log->message('Test line');
  71. $this->assertTrue(
  72. preg_match('/(\d+)/', $this->getFileLine('../temp/test.log', 0), $matches),
  73. 'Found timestamp');
  74. $clock = new clock();
  75. $this->assertSameTime((integer)$matches[1], $clock->now(), 'Correct time');
  76. }</strong>
  77. }
  78. ?>
  79. ]]></php>
  80. The test case creates a new <code>Log</code>
  81. object and writes a message.
  82. We look for a digit sequence and then test it against the current
  83. time using our <code>Clock</code> object.
  84. Of course it doesn&apos;t work until we write the code.
  85. <div class="demo">
  86. <h1>All tests</h1>
  87. <span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]<br />
  88. <span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]<br />
  89. <span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->Created before message<br />
  90. <span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->File created<br />
  91. <span class="fail">Fail</span>: log_test.php->Log class test->testtimestamps->Found timestamp<br />
  92. <br />
  93. <b>Notice</b>: Undefined offset: 1 in <b>/home/marcus/projects/lastcraft/tutorial_tests/tests/log_test.php</b> on line <b>44</b><br />
  94. <span class="fail">Fail</span>: log_test.php->Log class test->testtimestamps->Correct time<br />
  95. <span class="pass">Pass</span>: clock_test.php->Clock class test->testclockadvance->Advancement<br />
  96. <span class="pass">Pass</span>: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
  97. <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">3/3 test cases complete.
  98. <strong>6</strong> passes and <strong>2</strong> fails.</div>
  99. </div>
  100. The test suite is still showing the passes from our earlier
  101. modification.
  102. </p>
  103. <p>
  104. We can get the tests to pass simply by adding a timestamp
  105. when writing out to the file.
  106. Yes, of course all of this is trivial and
  107. I would not normally test this fanatically, but it is going
  108. to illustrate a more general problem.
  109. The <em>log.php</em> file becomes...
  110. <php><![CDATA[
  111. <?php<strong>
  112. require_once('../classes/clock.php');</strong>
  113. class Log {
  114. var $_file_path;
  115. function Log($file_path) {
  116. $this->_file_path = $file_path;
  117. }
  118. function message($message) {<strong>
  119. $clock = new Clock();</strong>
  120. $file = fopen($this->_file_path, 'a');<strong>
  121. fwrite($file, "[" . $clock->now() . "] $message\n");</strong>
  122. fclose($file);
  123. }
  124. }
  125. ?>
  126. ]]></php>
  127. The tests should now pass.
  128. </p>
  129. <p>
  130. Our new test is full of problems, though.
  131. What if our time format changes to something else?
  132. Things are going to be a lot more complicated to test if this
  133. happens.
  134. It also means that any changes to the clock class time
  135. format will cause our logging tests to fail also.
  136. This means that our log tests are tangled up with the clock tests
  137. and extremely fragile.
  138. It lacks cohesion, which is the same as saying it is not
  139. tightly focused, testing facets of the clock as well as the log.
  140. Our problems are caused in part because the clock output
  141. is unpredictable when
  142. all we really want to test is that the logging message
  143. contains the output of
  144. <code>Clock::now()</code>.
  145. We don&apos;t
  146. really care about the contents of that method call.
  147. </p>
  148. <p>
  149. Can we make that call predictable?
  150. We could if we could get the log to use a dummy version
  151. of the clock for the duration of the test.
  152. The dummy clock class would have to behave the same way
  153. as the <code>Clock</code> class
  154. except for the fixed output from the
  155. <code>now()</code> method.
  156. Hey, that would even free us from using the
  157. <code>TimeTestCase</code> class!
  158. </p>
  159. <p>
  160. We could write such a class pretty easily although it is
  161. rather tedious work.
  162. We just create another clock class with same interface
  163. except that the <code>now()</code> method
  164. returns a value that we can change with some other setter method.
  165. That is quite a lot of work for a pretty minor test.
  166. </p>
  167. <p>
  168. Except that it is really no work at all.
  169. </p>
  170. </section>
  171. <section name="mock" title="A mock clock">
  172. <p>
  173. To reach instant testing clock nirvana we need
  174. only three extra lines of code...
  175. <php><![CDATA[
  176. require_once('simpletest/mock_objects.php');
  177. ]]></php>
  178. This includes the mock generator code.
  179. It is simplest to place this in the <em>all_tests.php</em>
  180. script as it gets used rather a lot.
  181. <php><![CDATA[
  182. Mock::generate('Clock');
  183. ]]></php>
  184. This is the line that does the work.
  185. The code generator scans the class for all of its
  186. methods, creates code to generate an identically
  187. interfaced class, but with the name &quot;Mock&quot; added,
  188. and then <code>eval()</code>s the new code to
  189. create the new class.
  190. <php><![CDATA[
  191. $clock = &new MockClock($this);
  192. ]]></php>
  193. This line can be added to any test method we are interested in.
  194. It creates the dummy clock ready to receive our instructions.
  195. </p>
  196. <p>
  197. Our test case is on the first steps of a radical clean up...
  198. <php><![CDATA[
  199. <?php
  200. require_once('../classes/log.php');
  201. require_once('../classes/clock.php');<strong>
  202. Mock::generate('Clock');
  203. class TestOfLogging extends UnitTestCase {
  204. function TestOfLogging() {
  205. $this->UnitTestCase('Log class test');
  206. }</strong>
  207. function setUp() {
  208. @unlink('../temp/test.log');
  209. }
  210. function tearDown() {
  211. @unlink('../temp/test.log');
  212. }
  213. function getFileLine($filename, $index) {
  214. $messages = file($filename);
  215. return $messages[$index];
  216. }
  217. function testCreatingNewFile() {
  218. ...
  219. }
  220. function testAppendingToFile() {
  221. ...
  222. }
  223. function testTimestamps() {<strong>
  224. $clock = &new MockClock($this);
  225. $clock->setReturnValue('now', 'Timestamp');
  226. $log = new Log('../temp/test.log');
  227. $log->message('Test line', &$clock);
  228. $this->assertWantedPattern(
  229. '/Timestamp/',
  230. $this->getFileLine('../temp/test.log', 0),
  231. 'Found timestamp');</strong>
  232. }
  233. }
  234. ?>
  235. ]]></php>
  236. This test method creates a <code>MockClock</code>
  237. object and then sets the return value of the
  238. <code>now()</code> method to be the string
  239. &quot;Timestamp&quot;.
  240. Every time we call <code>$clock->now()</code>
  241. it will return this string.
  242. This should be easy to spot.
  243. </p>
  244. <p>
  245. Next we create our log and send a message.
  246. We pass into the <code>message()</code>
  247. call the clock we would like to use.
  248. This means that we will have to add an optional parameter to
  249. the logging class to make testing possible...
  250. <php><![CDATA[
  251. class Log {
  252. var $_file_path;
  253. function Log($file_path) {
  254. $this->_file_path = $file_path;
  255. }
  256. function message($message, <strong>$clock = false</strong>) {<strong>
  257. if (!is_object($clock)) {
  258. $clock = new Clock();
  259. }</strong>
  260. $file = fopen($this->_file_path, 'a');
  261. fwrite($file, "[" . $clock->now() . "] $message\n");
  262. fclose($file);
  263. }
  264. }
  265. ]]></php>
  266. All of the tests now pass and they test only the logging code.
  267. We can breathe easy again.
  268. </p>
  269. <p>
  270. Does that extra parameter in the <code>Log</code>
  271. class bother you?
  272. We have changed the interface just to facilitate testing after
  273. all.
  274. Are not interfaces the most important thing?
  275. Have we sullied our class with test code?
  276. </p>
  277. <p>
  278. Possibly, but consider this.
  279. Next chance you get, look at a circuit board, perhaps the motherboard
  280. of the computer you are looking at right now.
  281. On most boards you will find the odd empty hole, or solder
  282. joint with nothing attached or perhaps a pin or socket
  283. that has no obvious function.
  284. Chances are that some of these are for expansion and
  285. variations, but most of the remainder will be for testing.
  286. </p>
  287. <p>
  288. Think about that.
  289. The factories making the boards many times over wasting material
  290. on parts that do not add to the final function.
  291. If hardware engineers can make this sacrifice of elegance I am
  292. sure we can too.
  293. Our sacrifice wastes no materials after all.
  294. </p>
  295. <p>
  296. Still bother you?
  297. Actually it bothers me too, but not so much here.
  298. The number one priority is code that works, not prizes
  299. for minimalism.
  300. If it really bothers you, then move the creation of the clock
  301. into another protected factory method.
  302. Then subclass the clock for testing and override the
  303. factory method with one that returns the mock.
  304. Your tests are clumsier, but your interface is intact.
  305. </p>
  306. <p>
  307. Again I leave the decision to you.
  308. </p>
  309. </section>
  310. </content>
  311. <internal>
  312. <link>
  313. <a href="#refactor">Refactoring the tests</a> so we can reuse
  314. our new time test.
  315. </link>
  316. <link>Adding <a href="#timestamp">Log timestamps</a>.</link>
  317. <link><a href="#mock">Mocking the clock</a> to make the test cohesive.</link>
  318. </internal>
  319. <external>
  320. <link>
  321. This follows the <a href="first_test_tutorial.php">unit test tutorial</a>.
  322. </link>
  323. <link>
  324. Next is distilling <a href="boundary_classes_tutorial.php">boundary classes</a>.
  325. </link>
  326. <link>
  327. You will need the <a href="simple_test.php">SimpleTest</a>
  328. tool to run the examples.
  329. </link>
  330. <link>
  331. <a href="http://www.mockobjects.com/">Mock objects</a> papers.
  332. </link>
  333. </external>
  334. <meta>
  335. <keywords>
  336. software development,
  337. php programming,
  338. programming php,
  339. software development tools,
  340. php tutorial,
  341. free php scripts,
  342. architecture,
  343. php resources,
  344. mock objects,
  345. junit,
  346. php testing,
  347. unit test,
  348. php testing
  349. </keywords>
  350. </meta>
  351. </page>