<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Web Mozarts &#187; Best Practices</title>
	<atom:link href="http://webmozarts.com/category/best-practices/feed/" rel="self" type="application/rss+xml" />
	<link>http://webmozarts.com</link>
	<description>On The Art Of Web Development</description>
	<lastBuildDate>Tue, 06 Mar 2012 16:35:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Creating mobile symfony sites</title>
		<link>http://webmozarts.com/2010/09/07/creating-mobile-symfony-sites/</link>
		<comments>http://webmozarts.com/2010/09/07/creating-mobile-symfony-sites/#comments</comments>
		<pubDate>Tue, 07 Sep 2010 08:02:25 +0000</pubDate>
		<dc:creator>Klemens</dc:creator>
				<category><![CDATA[Best Practices]]></category>

		<guid isPermaLink="false">http://webmozarts.com/?p=518</guid>
		<description><![CDATA[Stumbling over a post in the symfony-users list I wrote down some information on how we manage mobile sites in our ullright platform: There&#8217;s an old blog post about creating an symfony iPhone view: http://www.symfony-project.org/blog/2008/06/09/how-to-create-an-optimized-version-of-your-website-for-the-iphone-in-symfony-1-1 Most of it is still valid and it works. But there is one serious drawback: You have to provide a [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>Stumbling over a post in the symfony-users list I wrote down some information on how we manage mobile sites in our ullright platform:</p>
<p>There&#8217;s an old blog post about creating an symfony iPhone view:<br />
<a href="http://www.symfony-project.org/blog/2008/06/09/how-to-create-an-optimized-version-of-your-website-for-the-iphone-in-symfony-1-1" target="_blank" class="liexternal">http://www.symfony-project.org/blog/2008/06/09/how-to-create-an-optimized-version-of-your-website-for-the-iphone-in-symfony-1-1</a><br />
Most of it is still valid and it works.</p>
<p>But there is one serious drawback: You have to provide a mobile template for each action.<br />
That&#8217;s why we created a tiny patch to provide a fallback to normal templates in case there is no special mobile one.</p>
<p>Here are the required parts:</p>
<p>Mobile detection: This belongs into your project configuration:<br />
<a href="http://trac.ullright.org/browser/trunk/plugins/ullCorePlugin/config/ullCorePluginConfiguration.class.php" target="_blank" class="liexternal">http://trac.ullright.org/browser/trunk/plugins/ullCorePlugin/config/ullCorePluginConfiguration.class.php</a></p>
<p>Symfony patch enabling fallback to html templates: (Patches sfView.class.php)<br />
<a href="http://trac.ullright.org/browser/trunk/plugins/ullCorePlugin/patch/sfView.patch.txt" target="_blank" class="liexternal">http://trac.ullright.org/browser/trunk/plugins/ullCorePlugin/patch/sfView.patch.txt</a></p>
<p>Finally provide a mobile template (or not):<br />
Normaly you would put your template in apps/frontend/modules/myModule/templates/myActionSuccess.php<br />
Now you can provide a mobile template by creating the following file: apps/frontend/modules/myModule/templates/myActionSuccess.mobile.php</p>
<p>This also works for layouts, partials and components. Example: apps/frontend/modules/myModule/templates/_head.mobile.php</p>
<p>Here&#8217;s the original post: <a href="http://groups.google.com/group/symfony-users/browse_thread/thread/9da0a9fe3cf3ff77" target="_blank" class="liexternal">http://groups.google.com/group/symfony-users/browse_thread/thread/9da0a9fe3cf3ff77</a></p>
<p>Have a nice day!</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://webmozarts.com/2010/09/07/creating-mobile-symfony-sites/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Why Not To Want 100% Code Coverage</title>
		<link>http://webmozarts.com/2010/03/15/why-not-to-want-100-code-coverage/</link>
		<comments>http://webmozarts.com/2010/03/15/why-not-to-want-100-code-coverage/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 08:00:20 +0000</pubDate>
		<dc:creator>Bernhard</dc:creator>
				<category><![CDATA[Best Practices]]></category>

		<guid isPermaLink="false">http://webmozarts.com/?p=484</guid>
		<description><![CDATA[Although most modern literature agrees that testing is essential for successful software projects, testing has to be done right. Several bad habits can be identified that not only negatively affect testing performance, but also reduce your development speed. One of the first mistakes people make when they first discover testing is trying to reach 100% [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>Although most modern literature agrees that testing is essential for successful software projects, testing has to be done right. Several bad habits can be identified that not only negatively affect testing performance, but also reduce your development speed. One of the first mistakes people make when they first discover testing is trying to reach 100% code coverage. I was no exception.<span id="more-484"></span></p>
<h3>Test Balance</h3>
<p>The more tests you have for your application, the more difficult it becomes to introduce changes. Everytime you change an existing feature, you have to change <em>at least</em> one test. Everytime you make a refactoring of your project&#8217;s architecture (which you should do frequently), you most likely need to adapt <em>multiple</em> tests. As a rule of thumb you can say that the more tests you have, the more difficult it becomes to make changes in your code.</p>
<p>We know that not to write tests is not a solution. Lots of tests, on the other hand, are bad for maintainability. Instead, try to keep a certain test balance by testing only what is important. The following section shows you one possible approach for identifying important tests called <em>risk-based testing</em>.</p>
<h3>Risk-Based Testing</h3>
<p>The purpose of testing is to avoid regressions in your software resulting of its complexity. These potential regressions can be expressed as risks ranked by their probability and severity. The probability expresses how likely the regression is to occur. The severity expresses how severely the regression would affect the functionality of your application. Both can be expressed in numbers, for instance in a range of 1 to 10 with 10 being the highest severity/probability. Look at the following table for example:</p>
<table border="0">
<tbody>
<tr>
<th>Risk</th>
<th>Probability (<em>P</em>)</th>
<th>Severity (<em>S</em>)</th>
<th>Total (<em>P</em>x<em>S</em>)</th>
</tr>
<tr>
<td><code>getGroup()</code> returns a wrong object</td>
<td>1</td>
<td>3</td>
<td>3</td>
</tr>
<tr>
<td><code>calculatePrice($product)</code> uses a wrong algorithm</td>
<td>7</td>
<td>8</td>
<td>56</td>
</tr>
</tbody>
</table>
<p>The table contains risks for two fictitious methods <code>getGroup()</code> and <code>calculatePrice()</code>. Imagine that the first of these methods only returns an internal property <code>$group</code>. The probability of someone breaking this code by accident is near to non-existent. Assume further that the group is only used for display purposes, so the severity of a broken code is not very high either.</p>
<p>The second method, <code>calculatePrice()</code>, uses an internal algorithm to calculate the price of a product. Because it depends on an external object <code>$product</code>, and because the algorithm is non-trivial, the probability of breaking the code is rather high. Even higher though is the severity of a broken functionality &#8211; what could be worse than wrongly calculated prices.</p>
<p>Is it worth to unit-test <code>getGroup()</code>? Probably not. We calculated an overall total of 3, which (in our scale from 1 to 100) is really not that impressive. Is it, on the other hand, worth to test <code>calculatePrice()</code>? Judge for yourself.</p>
<p>Obviously I selected two extreme examples here. Also you will almost never calculate probabilities and severities for testing single methods like I did it here. But you should try to develop a feeling for what is worth to be tested and what is not.</p>
<h3>Test Complexity</h3>
<p>Now that you have identified which risks you should cover in your test suite, the question is to what extent you should do so. Look at the following to approaches for testing <code>calculatePrice()</code>:</p>
<p><strong>Approach 1: The fair-enough approach</strong></p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$t</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> LimeTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: calculatePrice() multiplies the price with the amount</span>
&nbsp;
  <span style="color: #000088;">$product</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Product<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$product</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>price <span style="color: #339933;">=</span> <span style="color: #cc66cc;">100</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$product</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>amount <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>is<span style="color: #009900;">&#40;</span><span style="color: #000088;">$calculator</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>calculatePrice<span style="color: #009900;">&#40;</span><span style="color: #000088;">$product</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">200</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>Approach 2: The safe approach</strong></p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$t</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> LimeTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Before</span>
&nbsp;
  <span style="color: #000088;">$product</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Product<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$product</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>price <span style="color: #339933;">=</span> <span style="color: #cc66cc;">100</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: calculatePrice() multiplies the price with the amount (amount == 1)</span>
&nbsp;
  <span style="color: #000088;">$product</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>amount <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>is<span style="color: #009900;">&#40;</span><span style="color: #000088;">$calculator</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>calculatePrice<span style="color: #009900;">&#40;</span><span style="color: #000088;">$product</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: calculatePrice() multiplies the price with the amount (amount == 2)</span>
&nbsp;
  <span style="color: #000088;">$product</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>amount <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>is<span style="color: #009900;">&#40;</span><span style="color: #000088;">$calculator</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>calculatePrice<span style="color: #009900;">&#40;</span><span style="color: #000088;">$product</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">200</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The first approach assumes that testing whether the result equals price multiplied by amount is enough. The test can obviously not check whether the developer has hard-coded a fixed return value of 200 or uses a fixed amount of 2. It expects the developer to be <em>reasonable</em>.</p>
<p>The second approach takes care of these eventualities by writing another test to make sure that changed amounts result in changed outputs. But even now, the developer could write a simple switch statement in <code>calculatePrice()</code> and return either 100 or 200, based on the amount. The test will not notice.</p>
<p>The conclusion is that you can never test your code for <em>all</em> eventualities. However complicated your test may be, there will always be a way to fake the implementation. But is it likely that developers will fake it? Probably not. This being said, the best approach in my opinion is approach 1 because it keeps effort required to adapt or change the test to a minimum.</p>
<h3>Conclusion</h3>
<p>Don&#8217;t try to achieve 100% test coverage. Identify the most important risks, and test for those. Don&#8217;t test for all eventualities either. Always keep in mind that the developers working on your code are somewhat reasonable people. If they aren&#8217;t, you are probably better off without them anyway.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://webmozarts.com/2010/03/15/why-not-to-want-100-code-coverage/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Writing Efficient Tests</title>
		<link>http://webmozarts.com/2010/03/11/writing-efficient-tests/</link>
		<comments>http://webmozarts.com/2010/03/11/writing-efficient-tests/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 17:55:06 +0000</pubDate>
		<dc:creator>Bernhard</dc:creator>
				<category><![CDATA[Best Practices]]></category>

		<guid isPermaLink="false">http://webmozarts.com/?p=469</guid>
		<description><![CDATA[Unit testing can be a blessing and curse at the same time. Once you start doing it on a regular basis, it can become an addiction. You test everything, you feel the satisfaction of 110% test coverage giving you confidence in your code. But after a while, testing suddenly seems to slow you down. Everytime [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>Unit testing can be a blessing and curse at the same time. Once you start doing it on a regular basis, it can become an addiction. You test everything, you feel the satisfaction of 110% test coverage giving you confidence in your code. But after a while, testing suddenly seems to slow you down. Everytime you make a change in your code you have to adapt several unrelated tests. Adding a <code>&lt;ul&gt;</code>-tag to your template becomes a matter of minutes, rather than seconds. And, worst of all, your test suite is <em>slow</em>.</p>
<p>What happened?<span id="more-469"></span></p>
<h3>Unit vs. System Tests</h3>
<p>To begin with, you need to understand the difference between unit and system tests and the impact both have on testing performance.</p>
<p>Unit tests are <em>atomic</em>. They test classes and components in isolation from any other service they depend on. Such services can be external services, like mailing systems, databases or webservices, and internal services, like a calculator, a data store or similar service classes. Running these tests in isolation gives you several advantages:</p>
<ul>
<li>Speed of execution</li>
<li>Speed of development</li>
<li>Test confidence</li>
</ul>
<p>Speed of execution, because the test doesn&#8217;t need to wait for the related service to process its internal logic. Speed of development, because you (hopefully) don&#8217;t have to adapt the test when you refactor the internals of the related service class or add new features to it. And test confidence, because the test will only fail when the tested class is erroneous, not if any of the related services provide wrong data.</p>
<p>System tests (acceptance or functional tests are a kind of system tests) test whether all the classes in your application collaborate correctly. Because you unit tested these classes in isolation, you had to <em>assume</em> how collaborating services should behave. If this assumption is wrong, no unit test will tell you. And that&#8217;s the space that system tests fill. The big, big disadavantage of system tests is that they are slow. They have to initialize the application, read its configuration files, initialize its database with fresh data (it doesn&#8217;t make a lot of sense to disconnect system tests from the real database) and more. All this takes time.</p>
<p>The conclusion from the last paragraphs is that <em>features</em> of your application should <em>always</em> be tested in unit tests. These tests are fast and guide you to the error if things go wrong. There is nothing more harmful to test performance than testing whether a form works correctly by means of a system test. If the form is a class, write a unit test. If the form is no class, make it one.</p>
<h3 style="font-size: 1,17em;">Decouple Your Code</h3>
<p>If you reach the point that you have lots of unit tests and few system tests, you made the first step towards becoming a test speed king. The second step is to decouple your classes.</p>
<p>Highly coupled code negatively affects your development in several ways. Because your code depends on other classes, these other classes (the dependent-on components or DOCs) all have to be instantiated during testing. Depending on their nature, this process may take time and slow your test down. Introducing new features becomes difficult because it results in lot of test code that needs to be adapted. If one of your classes breaks, not only the test of the class fails, but also several other tests of dependent classes. Shortly spoken: Extending and maintaining the application becomes a nightmare.</p>
<p>To decouple your code, get a clear picture of the responsibilities inside of your application. If a class does too much, tear it apart like a wild monkey smelling a banana in a big pile of waste paper.</p>
<p class="note">The following code samples are based on the PHP5 frameworks <a href="http://www.symfony-project.com" title="The symfony framework" target="_blank" class="liexternal">symfony</a>, <a href="http://www-doctrine-project.org" title="Doctrine Object-Relational Mapping for PHP5" target="_blank" class="liexternal">Doctrine</a> and <a href="http://github.com/bschussek/lime" title="Lime 2. A usable testing framework for PHP5." target="_blank" class="liexternal">Lime 2</a>. The same concepts can be applied to other frameworks and languages just as well.</p>
<p>Let&#8217;s look at a (slightly modified) example I recently saw in a code review:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> sfValidatorUsername
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> clean<span style="color: #009900;">&#40;</span><span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> Doctrine_Query<span style="color: #339933;">::</span><span style="color: #004000;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>from<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'User u'</span><span style="color: #009900;">&#41;</span>
      <span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>where<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'u.name = ? AND u.active = 1'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span>
      <span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>fetchOne<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">is_null</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorError<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'invalid'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$value</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It should be pretty obvious what this code is doing. What is the problem? The validator depends on the database. This is not a problem per se, but querying the database for <code>User</code> objects is beyond the validator&#8217;s responsibilities. This task should rather be done by your data acccess objects (DAOs), entity stores, tables or whatever you call them. And these objects can easily be injected into the validator using <em>Dependency Injection</em>.</p>
<p>Happy that we have identified this code smell, we can already start removing it:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> sfValidatorUsername
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000088;">$table</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span>UserTable <span style="color: #000088;">$table</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>table <span style="color: #339933;">=</span> <span style="color: #000088;">$table</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> clean<span style="color: #009900;">&#40;</span><span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">is_null</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>table<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>findActive<span style="color: #009900;">&#40;</span><span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorError<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'invalid'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$value</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>We removed the database code and instead inject the table object into the constructor. The responsibility for fetching an active user by its name was outsourced to the table.</p>
<p class="info">An even faster solution is to only count the matching user objects in the database instead of querying and hydrating them. But that&#8217;s not in the scope of this article.</p>
<p>So, mummy, is our test faster already? Is it?</p>
<h3>Replace Dependencies During Testing</h3>
<p>No, kid. We are still using the <code>UserTable</code> when testing the validator &#8211; of course, because we need it. So what can we do?</p>
<p>Now that the validator only depends on the <code>UserTable</code>, and not on some mystical database query magic, we can replace the <code>UserTable</code> &#8211; which is tested somewhere else and assumed to be working &#8211; with a fake implementation. This is usually called <em>stubbing</em> (because you are replacing it with a non-functional <em>stub</em>). With Lime 2, you can do it like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$t</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> LimeTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: clean() returns the cleaned value if the user is found</span>
&nbsp;
  <span style="color: #000088;">$table</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>stub<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'UserTable'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$table</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>findActive<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'bob'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>returns<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> User<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$table</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>replay<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$validator</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorUsername<span style="color: #009900;">&#40;</span><span style="color: #000088;">$table</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>is<span style="color: #009900;">&#40;</span><span style="color: #000088;">$validator</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>clean<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'bob'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'bob'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The stub acts <em>as if</em> it was the real <code>UserTable</code> object, but in reality it has no internal logic at all. So compared to the real table, the stub is very fast.</p>
<p class="info">More documentation about Lime 2 and its stubbing/mocking capabilities can currently be found on the <a href="http://github.com/bschussek/lime/tree/master/doc/" target="_blank" class="liexternal">Lime 2 GitHub repository</a>.</p>
<p>A word of caution shall be spoken. You should only replace <em>services</em> (classes that process some data and return a result) with stubs, not <em>entities</em> (classes that simply contain data). Otherwise changing your domain model (the entities) will soon become a nightmare.</p>
<h3>Testing With Databases</h3>
<p>Hurray! The validator test is so fast, I can execute it 10 times in a row and it&#8217;s still fun. One more time! Nice.</p>
<p>But wait &#8211; we can&#8217;t decouple everything from the database, can we? Of course, we can&#8217;t. Code that is responsible for collaborating with the database, like the above <code>UserTable</code>, needs to access the database. In order for that test to work, the database has to be bootstrapped and filled with data. Because tests should run in isolation from each other, the database further needs to be reset <em>before every single test</em>.</p>
<p>Now a common mistake that severely affects testing performance can often be seen in <em>symfony</em> projects. Many developers use a test database on their development DBMS, like a MySQL server. This database is filled with the content of <em>fixtures.yml</em>, which usually contains all fixture data commonly used to test the application in the browser. And for good reasons this is very slow:</p>
<ul>
<li>Most DBMS store data on the file system. Hard disk access is an expensive operation.</li>
<li>Filling the database with all the test data takes a lot of time</li>
<li>Parsing YAML files is slow</li>
</ul>
<p>So ideally we don&#8217;t use the database and don&#8217;t use any test data. Obviously, that&#8217;s not possible.</p>
<h3>In-Memory Databases</h3>
<p>What <em>is</em> possible is to use an in-memory database. While CPU access on the hard disk usually takes around 4 170 000 ns (nano seconds) for 7200 RPM drives, memory access only takes around 14 ns! Thus, using an in-memory database is a very cheap way to increase your testing performance immensely. Unfortunately not all database vendors offer in-memory alternatives for their file-based DBMS (such as MySQL). In such cases I use SQLite in-memory databases, because SQLite supports most of the SQL92 standard, which is generally sufficient for testing purposes.</p>
<p>If you use <em>symfony</em> with <em>Doctrine</em>, you can place the following code snippet into your <em>bootstrap/unit.php</em> file which initializes the SQLite in-memory database:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// initialize Doctrine</span>
<span style="color: #000088;">$cacheFile</span> <span style="color: #339933;">=</span> <span style="color: #990000;">sprintf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'sf_autoload_unit_doctrine_%s.data'</span><span style="color: #339933;">,</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">__FILE__</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$autoload</span> <span style="color: #339933;">=</span> sfSimpleAutoload<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">sys_get_temp_dir</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">'/'</span><span style="color: #339933;">.</span><span style="color: #000088;">$cacheFile</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$autoload</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>addDirectory<span style="color: #009900;">&#40;</span>ROOT_DIR<span style="color: #339933;">.</span><span style="color: #0000ff;">'/lib/model'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$autoload</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>addDirectory<span style="color: #009900;">&#40;</span>ROOT_DIR<span style="color: #339933;">.</span><span style="color: #0000ff;">'/lib/form'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$autoload</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>addDirectory<span style="color: #009900;">&#40;</span>ROOT_DIR<span style="color: #339933;">.</span><span style="color: #0000ff;">'/lib/filter'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$autoload</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>register<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$database</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> sfDoctrineDatabase<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
  <span style="color: #0000ff;">'name'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'doctrine'</span><span style="color: #339933;">,</span>
  <span style="color: #0000ff;">'dsn'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'sqlite::memory:'</span>
<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// load all missing model files</span>
Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">loadModels</span><span style="color: #009900;">&#40;</span>ROOT_DIR<span style="color: #339933;">.</span><span style="color: #0000ff;">'/lib/model'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * Reloads the database.
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> reload<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// close the connection to the in-memory database to recreate the database</span>
  Doctrine_Manager<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getCurrentConnection<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>close<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// create the database tables from the loaded models</span>
  Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">createTablesFromModels</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// clear the Doctrine cache</span>
  <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span>Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">getLoadedModels</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$model</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">getTable</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$model</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>clear<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p class="info">Make sure the constant <code>ROOT_DIR</code> is defined and points to the root of the tested project (your real project or the fixture project).</p>
<p class="note">You might wonder why the <code>$cacheFile</code> is required. This parameter allows us to run multiple tests in parallel while still leveraging autoloading performance by using a cache.</p>
<p>The real interesting piece of code is the <code>reload()</code> function. It allows you to recreate the database on demand. Whenever you write a test that requires a fresh database, call <code>reload()</code> and you are good to go.</p>
<h3>Fixture Management</h3>
<p>As described above, it is important to keep an eye on the test data that is loaded into your database. The more data you load, the more time it takes. Loading the whole <em>fixtures.yml</em> is a recipe for slow (not only because it contains a lot of data, but also because the YAML file must be parsed).</p>
<p>A much more efficient solution is to programmatively create and load test data on-the-fly. Only create what you need, and nothing more. Below you can find a sample test for our above method <code>UserTable::findActive()</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$t</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> LimeTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: findActive() returns an active user by username</span>
&nbsp;
  reload<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> User<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$user</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>username <span style="color: #339933;">=</span> <span style="color: #0000ff;">'bob'</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$user</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>active <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$user</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>save<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$table</span> <span style="color: #339933;">=</span> Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">getTable</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'User'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>is<span style="color: #009900;">&#40;</span><span style="color: #000088;">$table</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>findActive<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'bob'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$user</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This test is really fast now. The database is created in-memory, exactly one single <code>User</code> object is inserted and that&#8217;s it. The downside is that creating all the fixture data inline becomes a little messy, especially if you have to fill a lot of properties only because they are defined as <code>NOT NULL</code> in the database.</p>
<h3>Creation Methods</h3>
<p>To work around this issue, I prefer the <em>Creation Method</em> pattern by Gerard Meszaros[1]:</p>
<blockquote><p>We should use a <em>Creation Method</em> whenever consructing a <em>Fresh Fixture</em> requires significant complexity and we value <em>Tests as Documentation</em>.</p></blockquote>
<p>The pattern is very simple. Encapsulate the code required to create an object within a utility function that can be reused across your project. My rule of thumb is to write creation methods for all tested Doctrine records and initialize all <code>NOT NULL</code> fields and relations with default values so that the object can be saved without further modification. Because this leads to a lot of code duplication, I also use a base function <code>createObject()</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> createUser<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span> <span style="color: #000088;">$properties</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">return</span> createObject<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'User'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$properties</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #666666; font-style: italic;">// NOT NULL properties</span>
    <span style="color: #0000ff;">'username'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'francis'</span><span style="color: #339933;">,</span>
    <span style="color: #339933;">...</span>
    <span style="color: #666666; font-style: italic;">// NOT NULL relations</span>
    <span style="color: #0000ff;">'Group'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> createGroup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #339933;">...</span>
  <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> createObject<span style="color: #009900;">&#40;</span><span style="color: #000088;">$class</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span> <span style="color: #000088;">$properties</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span> <span style="color: #000088;">$defaultProperties</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$properties</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_merge</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$defaultProperties</span><span style="color: #339933;">,</span> <span style="color: #000088;">$properties</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000088;">$object</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000088;">$class</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$properties</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$property</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$object</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>set<span style="color: #009900;">&#40;</span><span style="color: #000088;">$property</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #b1b100;">return</span> <span style="color: #000088;">$object</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now you can call <code>createUser()</code> everytime you need to create and save a new <code>User</code> object. Optionally, you can inject property values into the constructor.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$t</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> LimeTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: findActive() returns an active user by username</span>
&nbsp;
  reload<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> createUser<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'username'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'bob'</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'active'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">,</span>
  <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$user</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>save<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$table</span> <span style="color: #339933;">=</span> Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">getTable</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'User'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>is<span style="color: #009900;">&#40;</span><span style="color: #000088;">$table</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>findActive<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'bob'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$user</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<div class="info">
<h4>A Few More Utility Methods</h4>
<p>In the following snippet you can find some more utility methods that I find very useful when dealing with fresh fixtures. Put them into your <em>bootstrap/unit.php</em> file or where ever they suit you best.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/**
 * Saves all objects passed as arguments.
 * @param Doctrine_Record $object1
 * @param Doctrine_Record ...
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> save<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">func_get_args</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$object</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$object</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>save<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * Creates a collection containing the passed objects.
 * @param Doctrine_Record $object1
 * @param Doctrine_Record ...
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> collection<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">func_num_args</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> LogicException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'You must pass at least one object'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000088;">$objects</span> <span style="color: #339933;">=</span> <span style="color: #990000;">func_get_args</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$collection</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Doctrine_Collection<span style="color: #009900;">&#40;</span><span style="color: #990000;">get_class</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$objects</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$objects</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$object</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$collection</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>add<span style="color: #009900;">&#40;</span><span style="color: #000088;">$object</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #b1b100;">return</span> <span style="color: #000088;">$collection</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The functions can be used like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$user1</span> <span style="color: #339933;">=</span> createUser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$user2</span> <span style="color: #339933;">=</span> createUser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$user3</span> <span style="color: #339933;">=</span> createUser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
save<span style="color: #009900;">&#40;</span><span style="color: #000088;">$user1</span><span style="color: #339933;">,</span> <span style="color: #000088;">$user2</span><span style="color: #339933;">,</span> <span style="color: #000088;">$user3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$coll</span> <span style="color: #339933;">=</span> collection<span style="color: #009900;">&#40;</span><span style="color: #000088;">$user1</span><span style="color: #339933;">,</span> <span style="color: #000088;">$user3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// etc.</span></pre></div></div>

</div>
<h3>Pulling All Levers</h3>
<p>Now that we have optimized our test code to the highest degree, there is one last thing we can do: Increase the hardware power of the test computers and optimize the test suite to utilize its power.</p>
<p>Because most CPUs nowadays feature multiple cores, you should design your test suite for parallel processing. Make sure that no two tests are using the same resources (another benefit of the in-memory databases) and use a testing framework of your choice that supports multiprocessing.</p>
<p>Lime 2, for example, supports multiprocessing by adding the <code>--processes</code> option:</p>
<pre class="code">$ php lime --processes=16</pre>
<p>While most of my CPU cores are pretty bored when running the test suite in one process, using multiple processes sparks a sudden increase in activity. Not only that, I could record speed increases of over 300% (15 minutes in one process, 4.5 minutes in 16 processes).</p>
<h3>Conclusion</h3>
<p>As I have tried to portray in this article, writing tests alone is not enough to improve your development. If tests are slow or prevent change, your developers won&#8217;t run and use them. Fortunately there are several ways to make changes easier and to increase test speed.</p>
<p>To summarize:</p>
<ol>
<li>Test single features in unit tests. System tests should only be used to verify whether the classes collaborate correctly within different processes.</li>
<li>Decouple your classes. This allows introduction of changes without having to adapt multiple tests.</li>
<li>Only classes that really need to should deal with remote services. Replace these classes with stubs in all other tests.</li>
<li>Choose the fastest version of a remote service available. When you test database classes, use in-memory databases.</li>
<li>Only create databases during testing when you really need them</li>
<li>Only load data into the database that you really need. Do so programmatively without taking the overhead of parsing XML or YAML files.</li>
<li>Make use of multiprocessing, if supported by your testing framework.</li>
</ol>
<p>How is your testing experience? Are you satisfied with the performance of your tests?</p>
<h3>References</h3>
<p>[1] Gerard Meszaros: <em>xUnit Test Patterns. Refactoring Test Code</em>. Addison-Wesley, 2007. Page 415</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://webmozarts.com/2010/03/11/writing-efficient-tests/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Why sfContext::getInstance() Is Bad</title>
		<link>http://webmozarts.com/2009/07/01/why-sfcontextgetinstance-is-bad/</link>
		<comments>http://webmozarts.com/2009/07/01/why-sfcontextgetinstance-is-bad/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 07:24:31 +0000</pubDate>
		<dc:creator>Bernhard</dc:creator>
				<category><![CDATA[Best Practices]]></category>

		<guid isPermaLink="false">http://webmozarts.com/?p=380</guid>
		<description><![CDATA[The &#8220;default&#8221; context does not exist. Is there any symfony developer out there who never stumbled upon this dreadful error message? I doubt it. Recently, a lot of posts have been made on the user mailing list asking for explanations and fixes. A quick search on Google for the exact phrase even returns 480 results! [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<blockquote><p>The &#8220;default&#8221; context does not exist.</p></blockquote>
<p>Is there any symfony developer out there who never stumbled upon this dreadful error message? I doubt it. Recently, a lot of posts have been made on the <a href="http://groups.google.com/group/symfony-users" title="Symfony users Google Group" target="_blank" class="liexternal">user mailing list</a> asking for explanations and fixes. A quick search on Google for the exact phrase even returns 480 results!</p>
<p>The reason for this error is quite simple though: It&#8217;s because you used <code>sfContext::getInstance()</code>. And you should never do that.<span id="more-380"></span></p>
<h3>MVC and the Context</h3>
<p>The class <code>sfContext</code> is the glue of the <em>controller layer</em> in symfony. It keeps all the relevant controller classes together: <code>sfUser</code>, <code>sfResponse</code>, <code>sfRequest</code>, <code>sfController</code> as well as some others. The reason for its existence is simplicity. These classes now only need a reference to the context to access each other. The class <code>sfController</code>, for instance, contains a protected member variable <code>$context</code>, by which it can access all the other objects without having to store seperate references.</p>
<p><code>sfContext</code> implements the <a href="http://en.wikipedia.org/wiki/Singleton_pattern" title="The Singleton pattern at Wikipedia" target="_blank" rel="nofollow" class="liwikipedia">Singleton</a> design pattern. Thus you can retrieve one of the few context instances by calling <code>sfContext::getInstance()</code> with an optional first parameter: The name of the context. If the first parameter is not given, the name is assumed to be &#8220;default&#8221;. But <code>sfContext</code> is no real Singleton. No new instance will ever be created when you call <code>sfContext::getInstance()</code>. Instead, you need to call <code>sfContext::createInstance()</code> first. If you miss to do that, you will receive exactly the error at the introduction of my post.</p>
<h3>Why to Avoid Singletons</h3>
<p>The Singleton pattern is actually one of the worst design patterns by the Gang-of-Four[1]. Because you hard-code the name of the singleton class, you create a dependency that is hard and partially impossible to substitute from outside. As a result, your class becomes unflexible and very hard to unit-test. Let&#8217;s look at a common mistake:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Product
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> save<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>sfContext<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getUser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>hasAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'foobar'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// do something</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><em>Listing 1</em></p>
<p>This implementation bears the following problems:</p>
<h4>Problem #1: Flexibility</h4>
<p>If you have multiple <code>sfUser</code> instances, you are not able to tell the product on which instance it should depend. The product always fetches the instance registered in the context. Also, if the context is not available (for instance in console tasks), the <code>save()</code> method fails.</p>
<h4>Problem #2: Testability</h4>
<p>For testing the <code>Product</code> class, you have to create the context including all of its dependencies. That means parsing <code>factories.yml</code>, reading the configuration files, instantiating <code>sfController</code>, <code>sfRequest</code> and many more classes. Doing so adds substantial overhead to your tests and makes them slow and prone to errors. If any of the operations during the context instantiation fails, your <code>Product</code> test will suddenly fail, even if the class <code>Product</code> is perfectly fine!</p>
<h3>How to Avoid Singletons</h3>
<p>Instead of hard-coding the call to <code>sfContext::getInstance()</code>, you should pass the context object directly to the object that needs it. If you don&#8217;t even need the context, but only one of its references like the user, pass that object instead.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Product
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">function</span> setUser<span style="color: #009900;">&#40;</span>sfUser <span style="color: #000088;">$user</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>user <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> save<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>user instanceof sfUser <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>user<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>hasAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'foobar'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// do something</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><em>Listing 2</em></p>
<p>This technique is called <em>Dependency Injection</em>. If you are not familiar with Dependency Injection, I recommend you to read Fabien Potencier&#8217;s <a href="http://fabien.potencier.org/article/11/what-is-dependency-injection" title="What Is Dependency Injection by Fabien Potencier" target="_blank" class="liexternal">introduction to Dependency Injection</a>. Basically there are two ways two inject dependencies into an object:</p>
<h4>Constructor Injection</h4>
<p>This type of Dependency Injection is used when a dependency is <em>required</em>. Because the dependency needs to be passed in the constructor, no object can ever be created when this dependency is not fulfilled.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Product
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span>sfUser <span style="color: #000088;">$user</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>user <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><em>Listing 3</em></p>
<h4>Setter Injection</h4>
<p>This type of Dependency Injection is used when a dependency is <em>optional</em>. Because you can never be sure whether the setter has been called, you always have to verify whether the object exists before accessing its operations and properties, as we did in Listing 2.</p>
<p>Alternatively, you can also use setter injection for required dependencies if you can not override the constructor without breaking the class (this is the case for Doctrine records). In that case, you simply throw an exception if the dependency is not available.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Product
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> save<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>user instanceof sfUser<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> LogicException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'The user must be set before saving'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><em>Listing 4</em></p>
<h3>What You Gained</h3>
<p>Because you can now inject any user object into your class, you can test the <code>Product</code> class very easily:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> StubUser <span style="color: #000000; font-weight: bold;">extends</span> sfUser
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> hasAttribute<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$name</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">'foobar'</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>comment<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Products with the attribute &quot;foobar&quot; do something special upon saving'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000088;">$p</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Product<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$p</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setUser<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> StubUser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$p</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>save<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>is<span style="color: #009900;">&#40;</span><span style="color: #339933;">...</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><em>Listing 5</em></p>
<h3>Exceptions</h3>
<p>In very few cases, you cannot avoid accessing the context by using <code>sfContext::getInstance()</code>. This is almost always the case when symfony manages the construction of an object. If you configure symfony to use a custom object by modifying <code>factories.yml</code>, you still won&#8217;t be able to inject custom objects.</p>
<p class="info">This will change as soon as symfony uses the new <a href="http://components.symfony-project.org/dependency-injection/" title="Website of the Symfony Dependency Injection Component" target="_blank" class="liexternal">Dependency Injection container</a> for the construction of the core classes.</p>
<p>An example for this problem is extending <code>sfResponse</code>. You can tell symfony to use a custom response, but you cannot tell symfony to inject the context or other objects into it (except for if you write a custom <code>sfFactoryConfigHandler</code>). In this case, and because <code>sfResponse</code> is part of the <em>controller layer</em>, you should be pragmatic and just use <code>sfContext::getInstance()</code>.</p>
<h3>Conclusion</h3>
<p>Always try to avoid calling <code>sfContext::getInstance()</code>. Many of symfony&#8217;s classes in the <em>controller layer</em> already store a reference to the context, so you can use that one instead. If no reference is available, inject the reference to the context or to whichever class you need.</p>
<h3>References</h3>
<p>[1] E. Gamma, R. Helm, R. Johnson, J. Vlissides: <em>Design Patterns. Elements of Reusable Object-Oriented Software</em>. Addison-Wesley, 1995</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://webmozarts.com/2009/07/01/why-sfcontextgetinstance-is-bad/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
	</channel>
</rss>

