<?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; Development</title>
	<atom:link href="http://webmozarts.com/category/development/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>Symfony2 Form Architecture</title>
		<link>http://webmozarts.com/2012/03/06/symfony2-form-architecture/</link>
		<comments>http://webmozarts.com/2012/03/06/symfony2-form-architecture/#comments</comments>
		<pubDate>Tue, 06 Mar 2012 16:35:55 +0000</pubDate>
		<dc:creator>Bernhard</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://webmozarts.com/?p=524</guid>
		<description><![CDATA[Symfony2 features a brand-new Form component that, to my knowledge, supersedes most existing PHP form libraries in functionality and extensibility (not counting the still lacking, native JavaScript support). It has been in development for  two years, even though I was already thinking about it since 2009 and earlier. It is becoming more and more stable recently, [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p><a href="http://symfony.com/" title="Symfony2. A web development framework for PHP 5.3." target="_blank" class="liexternal">Symfony2</a> features a brand-new <a href="https://github.com/symfony/Form" title="The Symfony2 Form component. A compositional form library for PHP." target="_blank" class="liexternal">Form component</a> that, to my knowledge, supersedes most existing PHP form libraries in functionality and extensibility (not counting the still lacking, native JavaScript support). It has been in development for  two years, even though I was already <a href="http://webmozarts.com/2009/04/12/improving-the-forms/" title="Thoughts about improving the form layer in symfony 1." class="liinternal">thinking about it since 2009</a> and earlier. It is becoming more and more stable recently, with a first completely stable release expected for Symfony 2.2.</p>
<p>This post was partially triggered by the release of the new <a href="http://framework.zend.com/wiki/display/ZFDEV2/RFC+-+Forms" title="Zend Framework 2 RFC for Forms" target="_blank" class="liexternal">Zend Framework 2 Form RFC</a> because I think that a lot of duplicated effort is going on there. I completely understand that Zend Framework 2 needs a form layer that is tailored to the components delivered by the framework. The purpose of this post is to demonstrate that the Symfony2 Form component is perfectly suited for this requirement. Symfony2-specific functionality can be unplugged, leaving only the raw core dealing with form processing and abstraction. As a replacement, functionality can be developed for supporting Zend&#8217;s or any other framework&#8217;s components.</p>
<p>Creating a generic form library that elegantly solves all the various use-cases that can be found in web form construction and processing has been a challenging, long-lasting and complex task that is not over yet. Cooperating and continuing development from this common base on seems like a big chance to make form handling in PHP more powerful &#8211; and easier &#8211; than it has ever been before.</p>
<p><span id="more-524"></span>The post starts with crediting all the other great frameworks and form libraries that influenced this work. Then I would like to introduce you to the key aspects of the Form component before continuing to describe its high and low-level architecture.</p>
<div class="note">This post is not intended to show off the usage or killer features of the Form component. If you are looking for this, you can find examples and explanations in the <a href="http://symfony.com/doc/current/book/forms.html" title="The documentation of the Symfony2 Form component." target="_blank" class="liexternal">Form documentation</a>. Neither will this post explain what steps are necessary to use the Form component without Symfony2. This also has been covered, for example in <a href="https://gist.github.com/1170166" title="A Gist demonstrating how to use Symfony2 Forms without Symfony2." target="_blank" class="liexternal">this Gist</a>.</div>
<h3>Influences</h3>
<p>The Form component has been influenced by many other frameworks written in different languages, including <a href="http://www.symfony-project.com" title="The symfony web development framework for PHP." target="_blank" class="liexternal">symfony 1</a>, <a href="http://framework.zend.com/" title="The Zend Framework for PHP." target="_blank" class="liexternal">Zend Framework 1</a>, <a href="https://www.djangoproject.com/" title="The Django web framework for Python." target="_blank" class="liexternal">Django</a>, <a href="http://rubyonrails.org/" title="Ruby on Rails. A Ruby web development framework." target="_blank" class="liexternal">Ruby on Rails</a>,  <a href="http://struts.apache.org" title="The Apache Struts web development framework for Java." target="_blank" class="liexternal">Struts</a> and <a href="http://javaserverfaces.java.net" title="JavaServer Faces. A Java web development framework." target="_blank" class="liexternal">JSF</a>. Apart from that, it shows many similarities with <a href="http://groups.inf.ed.ac.uk/links/formlets/" title="Formlets. A form library for Links." target="_blank" class="liexternal">Formlets</a>, <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.206.496" title="Web User Interfaces. A form library for Curry." target="_blank" class="liexternal">WUI</a> and <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.81.5195" title="iData. A form library written in Clean." target="_blank" class="liexternal">iData</a>, form libraries written for the functional languages Links, Curry and Clean.</p>
<h3>Key Aspects</h3>
<p>The key aspects of the Form component are:</p>
<ul>
<li>Abstraction</li>
<li>Extensibility</li>
<li>Compositionality</li>
<li>Separation of Concerns</li>
<li>Model Binding</li>
<li>Dynamic Behavior</li>
</ul>
<div>I will give a short explanation for each of this aspects before I continue to explain how the component&#8217;s architecture realizes them.</div>
<h4>Abstraction</h4>
<p>Abstraction describes the ability to take any part of a form &#8211; or even the whole form &#8211; and put it into a reusable data structure. Consider a form with three drop down boxes to select the day, month and year  for a date. First, you need code that generates the HTML with all of its option tags. Second, you need code that converts from the application&#8217;s data type (for example, PHP&#8217;s <code>DateTime</code>) to the view&#8217;s representation (which option is selected?) and back. If you add another date selector to a form in your application, you need to duplicate and adapt all of that code.</p>
<p>Abstraction solves this problem by providing suitable data structures for describing and reusing your code.</p>
<h4>Extensibility</h4>
<p>Extensibility refers to two main concepts related to abstraction:</p>
<ol>
<li><em>Specialization</em> is a logical consequence of abstraction. When it is possible to abstract functionality into generic data structures, it should also be possible to <em>extend</em> these data structures into custom, specialized ones. A simple example is to extend the above date selector to also show selectors for the time. Without the ability to specialize the existing date selector, a large part of its functionality needs to be rewritten.</li>
<li><em>Mixins</em> are an orthogonal concept to specialization. Assume that you want to change all existing fields to include an asterisk (&#8220;*&#8221;) in their label if they require user input. Doing so by using specialization is a tedious task, because it requires you to <em>extend every existing field</em> with a custom one, implementing the same new functionality. <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.156.4510" title="Mixin-based Inheritance. Gilad Bracha and William Cook" target="_blank" class="liexternal">Mixins</a>, on the other hand, allow to attach functionality to existing objects without the need to specialize them. As a bonus, the added functionality is inherited by all descendants in the inheritance tree.</li>
</ol>
<p>Extensibility also refers to more indepth extensiblity by means of events, which will be discussed later.</p>
<h4>Compositionality</h4>
<p>If we examine the last examples a bit more, we discover that there is no relevant difference between<em> fields</em> (<em>complex</em> ones, such as in the example before, and <em>primitive</em> ones, such as a text input tag) and <em>forms</em>. Both fields and forms</p>
<ol>
<li>accept default values from the model (an array, a date, a string…)</li>
<li>convert the value to a representation suitable for use in the view</li>
<li>render HTML</li>
<li>accept values submitted by the user</li>
<li>convert these values back to the model&#8217;s format</li>
<li>optionally perform validation</li>
</ol>
<p>We can implement fields and forms using the same fundamental data structure. By adding compositionality &#8211; the ability to nest this data structure into itself (see the <a href="http://en.wikipedia.org/wiki/Composite_pattern" title="The Composite pattern at Wikipedia." target="_blank" rel="nofollow" class="liwikipedia">Composite pattern</a>) &#8211; we can create forms of arbitrary complexity. Instead of forms and fields, we will talk about <em>forms and their children</em> from now on. Once that a form has children, it also needs to</p>
<ol start="7">
<li>forward (<em>map</em>) its default value (an array or an object) to its children</li>
<li>extract (also <em>map</em>) the submitted value of each child back into the original array/object</li>
</ol>
<h4>Separation of Concerns</h4>
<p>We can group the tasks in the above list to several, distinct responsibilities:</p>
<ul>
<li>Data Transformation</li>
<li>HTML Generation (the <em>View</em>)</li>
<li>Validation</li>
<li>Data Mapping</li>
</ul>
<p>These responsibilities should be implemented by decoupled components with clearly defined interfaces. As a result, any of these components can be replaced by a custom implementation, such as a custom view or validator layer.</p>
<h4>Model Binding</h4>
<p>In many cases, forms directly relate to structures that have already been described otherwise in the <a href="http://en.wikipedia.org/wiki/Domain_model" title="Explanation about Domain Models on Wikipedia." target="_blank" rel="nofollow" class="liwikipedia">domain model</a>. Consider a form to submit the profile information of a user. Consider further that these profiles are stored in a table in your database. The table has information about the <em>properties</em> stored in the profile, about the <em>types</em> of these properties, their <em>default values</em> and their <em>constraints</em>. Ideally, your application also features a class <code>Profile</code> that is mapped to this database table with an <a href="http://en.wikipedia.org/wiki/Object-Relational_Mapping" title="Object-Relational Mappings on Wikipedia." target="_blank" rel="nofollow" class="liwikipedia">ORM</a> such as <a href="http://www.doctrine-project.org/" title="Doctrine 2. An Object-Relational Mapping for PHP." target="_blank" class="liexternal">Doctrine 2</a>. This class may exhibit more information about the profile, for example, that a profile can be related to any number of <em>subjects</em> that the user is intersted in. These subjects must be selected from a list that is stored in a configuration file.</p>
<p>Usually, the information listed here (we will call it <em>metadata</em>) must be replicated in the form layer. The user must know what properties he can edit, the form must display appropriate HTML widgets that correspond to the types of the properties, the user must know which fields may not be left empty and so on. <em>This is why creating forms usually sucks</em>.</p>
<p><em>Model Binding</em> tries to change this situation. It refers to two ideas:</p>
<ol>
<li><span class="Apple-style-span" style="font-style: normal;"><em>reuse existing metadata</em> during form construction in order to reduce duplication of code and configuration</span></li>
<li><em>read default values</em> from a domain object (an instance of <code>Profile</code>) and <em>write the submitted values</em> back into the object</li>
</ol>
<h4>Dynamic Behavior</h4>
<p>Last but not least, forms should support dynamic behavior. Gone are the times were you could statically code your forms on the server and avoid security issues by making sure that every submitted form corresponds to the predefined structure. Nowadays, client-side JavaScripts change the DOM of forms in order to enhance usability.</p>
<p>Just consider a tabular form. Each column contains fields of the same type, each row represents an object on the server. Little buttons allow to delete or to add new rows. Whenever the form is submitted, the server must adjust the form&#8217;s model to match the deleted and added rows in order to successfully process and validate it.</p>
<p>Dynamic behavior shouldn&#8217;t be restricted to tabular forms though. Suitable mechanisms in the architecture should allow reactions to any kind of change on the client. Unfortunately, this problem isn&#8217;t addressed by many libraries.</p>
<h3>High-Level Architecture</h3>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-565" title="The high-level architecture of the Symfony2 Form component." src="http://webmozarts.com/wp-content/uploads/2012/03/high-level-architecture.png" alt="" width="450" height="207" /></p>
<p>Let me outline the high-level architecture of forms in Symfony2. A their core lies the Form component. This component provides the basic architecture for defining and processing forms and uses Symfony2&#8242;s <a href="https://github.com/symfony/EventDispatcher" title="Symfony2's EventDispatcher component." target="_blank" class="liexternal">Event Dispatcher</a> internally for processing events. On top of the component lie a series of pluggable extensions:</p>
<ul>
<li>The <strong>Core</strong> extension provides all field definitions (called <em>form types</em>) implemented by the framework.</li>
<li>The <strong>Validation</strong> extension integrates the Symfony2 <a href="https://github.com/symfony/Validator" title="Symfony2's Validator component." target="_blank" class="liexternal">Validator</a> to implement form validation.</li>
<li>The <strong>DI</strong> extension adds support for Symfony2&#8242;s <a href="https://github.com/symfony/DependencyInjection" title="Symfony2's DependencyInjection component." target="_blank" class="liexternal">Dependency Injection</a> component.</li>
<li>The <strong>CSRF</strong> extension adds CSRF protection to forms.</li>
<li>The <strong>Doctrine 2</strong> extension (shipped with the <a href="https://github.com/symfony/DoctrineBridge" title="The Doctrine bridge for integrating Doctrine into Symfony2 components." target="_blank" class="liexternal">Doctrine bridge</a>) adds a Doctrine-specific drop down field and provides components that let forms know about Doctrine metadata.</li>
</ul>
<p>The topmost layer contains the components responsible for rendering HTML. Symfony2 provides two such components: One for rendering forms in <a href="http://twig.sensiolabs.org/" title="The Twig templating language for PHP." target="_blank" class="liexternal">Twig</a> (shipped with the <a href="https://github.com/symfony/TwigBridge" title="The Twig bridge integrating Twig into the Symfony2 components." target="_blank" class="liexternal">Twig bridge</a>) and another for rendering it with it&#8217;s <a href="https://github.com/symfony/Templating" title="Symfony2's Templating component for rendering PHP templates" target="_blank" class="liexternal">PHP Templating</a> component (contained in <a href="https://github.com/symfony/FrameworkBundle" title="Symfony2's FrameworkBundle on GitHub." target="_blank" class="liexternal">FrameworkBundle</a>).</p>
<p>The most interesting fact for other frameworks here is that every component apart from Form is replaceable. A custom extension could be written to support Zend Validator, another could be written for Smarty and so on. You could even go so far to remove the Core extension and write an own set of basic fields. Even the underlying Event Dispatcher can be replaced by writing a custom one that implements Symfony2&#8242;s <a href="https://github.com/symfony/EventDispatcher/blob/master/EventDispatcherInterface.php" title="Symfony2's EventDispatcherInterface." target="_blank" class="liexternal">EventDispatcherInterface</a>. You win a lot of flexibility compared to little loss.</p>
<h3>Low-Level Architecture</h3>
<p>This section continues to discuss the internal architecture of the Form component. As mentioned before, a form and all of its children can be represented by the same data structure that implements the Composite pattern. In the Form component, this data structure is described by the <code>FormInterface</code>. The main implementation of <code>FormInterface</code> is the class <code>Form</code>, which uses three components to do its work:</p>
<ul>
<li>A <strong>data mapper</strong> distributes the data of a form to its children and merges the data of the children back into the form&#8217;s data. The default data mapper allows forms to load their values both from arrays and objects or object graphs. After the form&#8217;s submission, the new values are written back into the original data structure.</li>
<li>Two <strong>chains of data transformers</strong> convert values between different representations. Data transformers guarantee to output values of predefined types to your application, regardless of the format used to display and modify the values in the view.</li>
<li>An<strong> event dispatcher</strong> allows you to execute custom code at predefined points during form processing. It enables you to adapt the form&#8217;s structure to match the submitted data, or to filter, modify or validate the submitted data and so on.</li>
</ul>
<p>These components are passed to the constructor of <code>Form</code> and cannot be changed after construction in order to avoid corruption of the form&#8217;s state. Because the constructor signature is quite long and complicated, a <strong>form builder</strong> simplifies the construction of <code>Form</code> instances.</p>
<p>The <strong>form view</strong> is the view representation of a form. This means that you never deal with <code>Form</code> instances in the template, but with <code>FormView</code> instances. These store additional, view-specific inforrmation, such as HTML names, IDs and so on.</p>
<p>The following UML diagram illustrates the architecture.</p>
<p style="text-align: center;"><img class="aligncenter" title="The UML class diagram of the Symfony2 Form component." src="http://webmozarts.com/wp-content/uploads/2012/03/class-diagram2.png" alt="" width="551" height="311" /></p>
<p>As can be seen in the previous diagram, a form has three different representations throughout its lifecycle:</p>
<ul>
<li>During construction, it is represented by a hierarchy of <code>FormBuilder</code> objects.</li>
<li>In the controller, it is represented by a hierarchy of <code>Form</code> objects.</li>
<li>In the view, it is represented by a hierarchy of <code>FormView</code> objects.</li>
</ul>
<p>Because the configuration of form builders and form views is repetitive, Symfony2 implements <strong>form types</strong> that group such configuration. Form types support dynamic inheritance, meaning that they can extend different base types, depending on the options passed at the the construction of a form. The following diagram illustrates all types that come bundled with the Symfony2 extensions (green types are provided by the Core extension, yellow types by additional ones):</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-585" title="Symfony2 form type hierachy." src="http://webmozarts.com/wp-content/uploads/2012/03/types.png" alt="" width="650" height="415" /></p>
<p>Mixins, as described before, are supported in Symfony2 by so-called <strong>type extensions</strong>. These type extensions can be attached to existing form types and add additional behavior. Symfony2, for example, contains type extensions for adding CSRF protection to the &#8220;form&#8221; type (and consequently all of its subtypes).</p>
<p>A <strong>form factory</strong> retrieves the type hierarchy from the loaded extensions and uses them to configure new <code>FormBuilder</code> and <code>FormView</code> objects. It is important to know that this configuration itself can be controlled by user-provided options. For example, the &#8220;choice&#8221; type supports an option &#8220;choices&#8221; in which all selectable values need to be passed.</p>
<p>The last important concept in the Form component is that of <strong>type guessers</strong>. Type guessers try to derive the type and options of a field in the form based on the metadata available for the domain object backing the form (if any). For example, if a property of the object is configured to be a one-to-many-relation to a model <code>Tag</code>, type guessers automatically configure this property to be represented by a multiple-choice field with all <code>Tag</code> instances loaded by default. This concept is similar to <a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/" title="Django documentation about ModelForms." target="_blank" class="liexternal">ModelForms</a> in Django. The main difference is that your application can use various type guessers to use metadata from different sources instead of just relying on the ORM definition. Symfony2, for example, ships with three guessers: One for reading Doctrine2 metadata, one for Propel metadata and a last one for reading metadata of the Symfony2 validator.</p>
<p>The concepts described in the last paragraphs are summarized again in the following UML diagram.</p>
<p style="text-align: center;"><img class="size-full wp-image-590 aligncenter" title="UML class diagram of the form factory." src="http://webmozarts.com/wp-content/uploads/2012/03/form-factory.png" alt="" width="533" height="331" /></p>
<h3>Summary</h3>
<p>As I have tried to show in this post, the Symfony2 Form component features a carefully engineered architecture that takes many important aspects of modern form processing into account.</p>
<p>It solves the problem of <em>abstraction</em>, <em>specialization</em> and <em>mixins</em> by providing a dynamic inheritance tree of form types and form type extensions. It solves the <em>compositionality</em> problem by distributing the work and responsibility of processing a form among all of its elements. It offers a clear <em>separation of concerns</em> in order to easily replace different layers of the component. It achieves <em>model binding</em> by involving the existing domain model metadata into the construction of a form and by reading from and writing into domain objects directly. And it supports <em>dynamic behavior</em> by offering events at predefined points during its processing that can be handled by custom listeners, such as for validation or filtering.</p>
<p>Interested? <a href="https://github.com/symfony/Form" title="Source code of the Symfony2 Form component." target="_blank" class="liexternal">Explore the code</a>. <a href="http://symfony.com/doc/current/book/forms.html" title="Symfony2 Forms documentation." target="_blank" class="liexternal">Play with it</a>. And help us to integrate it into your favourite framework.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://webmozarts.com/2012/03/06/symfony2-form-architecture/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Easy Unit Testing</title>
		<link>http://webmozarts.com/2009/06/30/easy-unit-testing/</link>
		<comments>http://webmozarts.com/2009/06/30/easy-unit-testing/#comments</comments>
		<pubDate>Tue, 30 Jun 2009 09:06:41 +0000</pubDate>
		<dc:creator>Bernhard</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://webmozarts.com/?p=334</guid>
		<description><![CDATA[Unit testing is a very important task of professional, scalable software development. Many tools exist to support unit testing in one or another way. All tools come with advantages and drawbacks. One of the best known test frameworks in the PHP world is PHPUnit. With the release of symfony, Fabien Potencier released another new testing [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>Unit testing is a very important task of professional, scalable software development. Many tools exist to support unit testing in one or another way. All tools come with advantages and drawbacks. One of the best known test frameworks in the PHP world is <a href="http://www.phpunit.de" title="Website of the test framework PHPUnit" target="_blank" class="liexternal">PHPUnit</a>. With the release of <a href="http://www.symfony-project.org" title="Official website of the web PHP framework &quot;symfony&quot;" target="_blank" class="liexternal">symfony</a>, <a href="http://fabien.potencier.org" title="Fabien Potencier's blog" target="_blank" class="liexternal">Fabien Potencier</a> released another new testing framework for PHP: <a href="http://trac.symfony-project.org/browser/tools/lime/trunk/lib/lime.php" title="Source code of the test framework &quot;lime&quot;" target="_blank" class="liexternal">lime</a>. The biggest advantage of <em>lime</em> over <em>PHPUnit</em> surely is the conciseness of the written test code. There are several disadvantages as well, which include bad test encapsulation due to the lack of support for fixture setup and teardown, and missing support for mock object generation.</p>
<p>Today I will briefly speak about the advantages of both frameworks, and how they can be combined to result in a slicker, powerful testing framework. I will show you how easy testing really can be! And you will be able to try it out, because all the required code has already been released in  <a href="http://www.symfony-project.org/plugins/sfLimeExtraPlugin" title="The symfony plugin sfLimeExtraPlugin" target="_blank" class="liexternal">sfLimeExtraPlugin</a>.</p>
<p><span id="more-334"></span></p>
<h3>Introduction</h3>
<p>In the following sections, I will refer to a set of example classes that I will briefly describe here for your better understanding:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> User
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000088;">$storage</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> User<span style="color: #009900;">&#40;</span>SessionStorageInterface <span style="color: #000088;">$storage</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>storage <span style="color: #339933;">=</span> <span style="color: #000088;">$storage</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> setAttribute<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><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;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>storage<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>write<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</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: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> getAttribute<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;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>storage<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>read<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</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>The <strong>user</strong> class offers methods to store data of a user in a <strong>session storage</strong> that you need to pass to its constructor.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">interface</span> SessionStorageInterface
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> write<span style="color: #009900;">&#40;</span><span style="color: #000088;">$key</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: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> read<span style="color: #009900;">&#40;</span><span style="color: #000088;">$key</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Let&#8217;s assume that <code>SessionStorageInterface</code> specifies how session storages have to look like. They need methods to write values into the underlying layer, be it the file system or database, and methods to read values.</p>
<p>We will be writing unit tests for the <code>User</code> class. We don&#8217;t want to use a real session storage class though, because we don&#8217;t want the test to rely on the file system or a database. Thus we will create a <em>fake implementation</em> of <code>SessionStorageInterface</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> StubSessionStorage implements SessionStorageInterface
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$name</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$value</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> write<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><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;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>name <span style="color: #339933;">=</span> <span style="color: #000088;">$name</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>value <span style="color: #339933;">=</span> <span style="color: #000088;">$value</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> read<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: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>name ? <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>value <span style="color: #339933;">:</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p class="note">Fake implementations like this are called &#8220;Stubs&#8221;. Obviously, they would never make sense in a production environment. Their sole purpose is to help us testing, as in our case, the <code>User</code> class.</p>
<h3>PHPUnit and the xUnit Family</h3>
<p>Back in 1999, <a href="http://www.threeriversinstitute.org/Kent%20Beck.htm" title="Kent Beck's page at the Three Rivers Institute" target="_blank" class="liexternal">Kent Beck</a> wrote &#8220;the mother of all unit          testing frameworks&#8221;; it was called &#8220;SUnit&#8221; and supported unit testing for <a href="http://en.wikipedia.org/wiki/Smalltalk" title="Smalltalk at Wikipedia" target="_blank" rel="nofollow" class="liwikipedia">Smalltalk</a>[1]. <a href="http://sunit.sourceforge.net" title="Unit testing framework for Smalltalk" target="_blank" class="liexternal">SUnit</a> lead to a further testing framework, that Beck wrote in cooperation with Erich Gamma: <a href="http://www.junit.org" title="Unit testing framework for Java" target="_blank" class="liexternal">jUnit</a>, for Java. Today, <em>jUnit</em> is the most popular and widely-used unit testing framework for Java and hence it was ported to many other languages: <em>CppUnit</em> for C++, <em>NUnit</em> for C# or <em>PHPUnit</em> for PHP. All those frameworks together are often referred to as the<strong> xUnit family</strong>[2].</p>
<p><a href="http://www.phpunit.de/" title="Website of the test framework PHPUnit" target="_blank" class="liexternal">PHPUnit</a> is a high-quality port of <em>jUnit</em> to PHP written by <a href="http://sebastian-bergmann.de" title="Sebastian Bergmann's personal website" target="_blank" class="liexternal">Sebastian Bergmann</a>, currently available in stable version 3.3. A typical test case with <em>PHPUnit</em> looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> UserTest <span style="color: #000000; font-weight: bold;">extends</span> PHPUnit_Framework_TestCase
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$sessionStorage</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$user</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> setUp<span style="color: #009900;">&#40;</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>sessionStorage <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StubSessionStorage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</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 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> User<span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>sessionStorage<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;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAttributesAreReadFromTheSession<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;">// fixture setup</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>sessionStorage<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>write<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Foo'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Bar'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// execute test</span>
    <span style="color: #000088;">$value</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<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// verify results</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>assertEquals<span style="color: #009900;">&#40;</span><span style="color: #000088;">$value</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Bar'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'The value was read from the session'</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;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAttributesAreWrittenToTheSession<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;">// ...</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>What does this code do? First of all, we see that the test code is organized within a <em>test class</em>. This means that you can use all the power of object-orientation for testing, but it also implies that a certain amount of code overhead is required for defining the class&#8217;s structure.</p>
<p>All methods prefixed with &#8220;test&#8221; are <em>test methods</em>. These methods test that a certain requirement is successfully fulfilled by the tested class. Because most of the test methods need a common set of objects (the &#8220;fixture&#8221;), these objects are created in the method <code>setUp()</code>, which is executed once before every test method. As a result, each test method works with fresh objects; influences of the previously executed test methods are largely prevented.</p>
<p>We also notice that test methods have descriptive names (which, to be honest, tend to look very weird). The purpose is to allow the reader to quickly scan the method names of a test class to receive an impression of the tested class&#8217;s abilities.</p>
<p>In our single, exemplary test method, we first set up the fixture; we tell the fake session storage, which has been instantiated in <code>setUp()</code>, to return the value &#8220;Bar&#8221; when the method <code>read("Foo")</code> is called. Then we call <code>getAttribute("Foo")</code> on the user, which we expect to read from the session. In the last line of code, we assert that the returned value has indeed been read from the session.</p>
<h3>Lime</h3>
<p><em>Lime</em> is a testing framework created by <a href="http://fabien.potencier.org/" title="Fabien Potencier's blog" target="_blank" class="liexternal">Fabien Potencier</a> for testing the source code of the web framework <a href="http://www.symfony-project.org/" title="Official website of the web PHP framework &quot;symfony&quot;" target="_blank" class="liexternal">symfony</a>. It is based on the <em>Test::More</em> Perl library and aims for a very concise and readable test code. The above test in <em>lime</em> looks 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> lime_test<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</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>comment<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Attributes are read from the session'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// fixture</span>
  <span style="color: #000088;">$s</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StubSessionStorage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$u</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: #000088;">$s</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$s</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>write<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Foo'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Bar'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">// test</span>
  <span style="color: #000088;">$value</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$u</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">// assertions</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;">$value</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Bar'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'The value was read from the session'</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>comment<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Attributes are written to the session'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// ...</span></pre></div></div>

<p>Contrary to <em>PHPUnit</em>, <em>lime</em> tests are written in a procedural way. Thus the code is more concise, because you don&#8217;t need to write down structural information of the code.</p>
<p>Initially a <code>lime_test</code> object is created, which tracks the number of expected, successful and failing tests and offers several methods to make testing easier. Each test case is, by convention, introduced by a comment that explains the tests purpose. Therefore the method <code>comment()</code> is called, which does also print the comment on the console when executing the test.</p>
<p>The test fixture has to be created manually for each test case. This is very prone to errors, because you can easily forget to reassign a variable once in a while. Then you&#8217;ll suddenly deal with an object left over from a previous test, which may lead to strange and unexpected test results.</p>
<h3>Pro and Contra</h3>
<p>Let us roughly sum up the advantages and disadvantages of both frameworks:</p>
<p><strong>PHPUnit&#8230;</strong></p>
<ul>
<li>&#8230; is verbose</li>
<li>&#8230; offers magic methods like <code>setUp()</code>, which initiates your test fixture before every test</li>
<li>&#8230; offers other convenient tools not covered in this blog post, like mocking support</li>
</ul>
<p><strong>lime&#8230;</strong></p>
<ul>
<li>&#8230; is concise and readable</li>
<li>&#8230; requires code repetition</li>
<li>&#8230; requires you to initiate your fixture manually</li>
</ul>
<p>sfLimeExtraPlugin extends <em>lime</em> and tries to introduce concepts of the xUnit family without making tests more verbose. Quite the opposite, because sfLimeExtraPlugin supports <em>annotations</em>, the written tests are even more concise than without this plugin.</p>
<h3>Annotation-Driven Tests</h3>
<p>The above test case, written with support of sfLimeExtraPlugin, looks 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> lime_test_simple<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Before</span>
<span style="color: #000088;">$s</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StubSessionStorage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$u</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: #000088;">$s</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: Attributes are read from the session</span>
<span style="color: #666666; font-style: italic;">// fixture</span>
<span style="color: #000088;">$s</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>write<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Foo'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Bar'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// test</span>
<span style="color: #000088;">$value</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$u</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// assertions</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;">$value</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Bar'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'The value was read from the session'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: Attributes are written to the session</span>
<span style="color: #666666; font-style: italic;">// ...</span></pre></div></div>

<p class="info">This test leads to <em>exactly the same</em> test results and console output as the test written with plain <em>lime</em> earlier in this post.</p>
<p>sfLimeExtraPlugin introduces the new class <code>lime_test_simple</code>. When you use that test class, you can mark sections of your code with so-called <a href="http://en.wikipedia.org/wiki/Java_annotation" title="Java annotations at Wikipedia" target="_blank" rel="nofollow" class="liwikipedia">annotations</a>. The test class knows, for example, that code annotated with <code>@Before</code> must be executed before every test case.</p>
<p>Single test cases are annotated with <code>@Test</code>. You can also add a comment about the purpose of the test. Note that the comment now really is a <em>PHP comment</em>, which is usually highlighted in a different color by code editors and thus disturbs the eye much less than the call to the method <code>comment()</code>.</p>
<p>Several other annotations are available. I&#8217;ll shortly list all of them:</p>
<dl>
<dt>@Test</dt>
<dd>A test case</dd>
<dt>@Before</dt>
<dd>Executed before each test case</dd>
<dt>@After</dt>
<dd>Executed after each test case</dd>
<dt>@BeforeAll</dt>
<dd>Executed once before all test cases</dd>
<dt>@AfterAll</dt>
<dd>Executed once after all test cases</dd>
</dl>
<p>With these annotations, you can easily structure your test code and avoid code duplication while making your tests easier to read.</p>
<h3>Testing for Exceptions</h3>
<p>Contrary to plain <code>lime_test</code>, <code>lime_test_simple</code> allows you to automatically test whether exceptions are thrown. With plain <code>lime_test</code>, such a test would look 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;">-&amp;</span>gt<span style="color: #339933;">;</span>comment<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'setAttribute() throws an exception if the data contains &amp;lt;script&amp;gt; tags'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// fixture</span>
  <span style="color: #000088;">$u</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: #000000; font-weight: bold;">new</span> StubSessionStorage<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: #666666; font-style: italic;">// test</span>
  try
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$u</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'&amp;lt;script&amp;gt;alert(&quot;Evil!&quot;)&amp;lt;/script&amp;gt;'</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>fail<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'setAttribute() throws an &quot;InvalidArgumentException&quot;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  catch <span style="color: #009900;">&#40;</span>InvalidArgumentException <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>pass<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'setAttribute() throws an &quot;InvalidArgumentException&quot;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></div></div>

<p>In this test, we try to catch the expected exception. If the exception is caught, we mark  the test as passed, otherwise as failed.</p>
<p>With <code>lime_test_simple</code>, this is much easier:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// @Before</span>
<span style="color: #000088;">$u</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: #000000; font-weight: bold;">new</span> StubSessionStorage<span style="color: #009900;">&#40;</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;">// @Test: setAttribute() throws an exception if the data contains &amp;lt;script&amp;gt; tags</span>
<span style="color: #666666; font-style: italic;">// fixture</span>
<span style="color: #000088;">$t</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>expect<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'InvalidArgumentException'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// test</span>
<span style="color: #000088;">$u</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'&amp;lt;script&amp;gt;alert(&quot;Evil!&quot;)&amp;lt;/script&amp;gt;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h3>Mock and Stub Objects</h3>
<p>Like <em>PHPUnit</em>, sfLimeExtraPlugin allows you to automatically generate fake objects, which are referred to as &#8220;Mocks&#8221; and &#8220;Stubs&#8221;. So far, we had to write our fake <code>StubSessionStorage</code> class by hand. With sfLimeExtraPlugin this is not needed anymore. The component <code>lime_mock</code> will generate such a class automatically:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// @Before</span>
<span style="color: #000088;">$s</span> <span style="color: #339933;">=</span> lime_mock<span style="color: #339933;">::</span><span style="color: #004000;">create</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'SessionStorageInterface'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$u</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: #000088;">$s</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// @Test: Attributes are read from the session</span>
<span style="color: #666666; font-style: italic;">// fixture</span>
<span style="color: #000088;">$s</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>read<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Foo'</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: #0000ff;">'Bar'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$s</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: #666666; font-style: italic;">// test</span>
<span style="color: #000088;">$value</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$u</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// assertions</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;">$value</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Bar'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'The value was read from the session'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Before the execution of each test case, we tell <code>lime_mock</code> to generate a new fake instance of <code>SessionStorageInterface</code>. In the test itself, we teach the fake object which methods can be called with what parameters and which value should be returned. We can also specify other constraints, such as how often a method may be called or which exception it should throw.</p>
<p>Then we switch the fake object into &#8220;replay&#8221; mode. In this mode, the fake object will behave just the way that we configured it before.</p>
<p class="note">You can create stubs for interfaces, classes or abstract classes. You can even create stubs for non-existing classes, which is very convenient if you develop test-driven.</p>
<p>Because this topic deserves a whole blog post of its own, I won&#8217;t go into more detail here. For more information about Mocks and Stubs in general and their usage in sfLimeExtraPlugin in specific can be found on the <a href="http://www.symfony-project.org/plugins/sfLimeExtraPlugin/0_2_0?tab=plugin_readme" title="Readme page of sfLimeExtraPlugin" target="_blank" class="liexternal">readme page</a> of sfLimeExtraPlugin.</p>
<h3>Final Words</h3>
<p>I personally think that tests can be written in a much more concise and readable way with sfLimeExtraPlugin. Because it also introduces other powerful features of the xUnit-family, the plugin aims to be an essential tool of every symfony developer who wants to seriously unit test his or her application.</p>
<p>Currently the plugin is available in version 0.2.0alpha. That means that the API may change before the final release (though this is unlikely) and that the code is not being considered 100% stable. I recommend you to try it out nevertheless and give me feedback about its usefulness or shortcomings, report bugs etc.</p>
<p>What do you think about sfLimeExtraPlugin? Do you think you may ever use it?</p>
<h3>References</h3>
<p>[1] Kent Beck, Donald G. Firesmith: <em>Kent Beck&#8217;s Guide to Better Smalltalk</em>. Cambridge University Press, 1998. Page 408</p>
<p>[2] Gerard Meszaros: <em>xUnit Test Patterns. Refactoring Test Code</em>. Addison-Wesley, 2007. Page 75</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://webmozarts.com/2009/06/30/easy-unit-testing/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
	</channel>
</rss>

