<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.1" -->
<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/"
	>

<channel>
	<title>CodeUtopia</title>
	<link>http://codeutopia.net/blog</link>
	<description>Web development and other things</description>
	<pubDate>Sat, 04 Jul 2009 16:26:59 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.1</generator>
	<language>en</language>
			<item>
		<title>Unit testing 5: test-driven development</title>
		<link>http://codeutopia.net/blog/2009/07/04/unit-testing-5-test-driven-development/</link>
		<comments>http://codeutopia.net/blog/2009/07/04/unit-testing-5-test-driven-development/#comments</comments>
		<pubDate>Sat, 04 Jul 2009 16:21:17 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/07/04/unit-testing-5-test-driven-development/</guid>
		<description><![CDATA[In this post I&#8217;ll introduce the methodology known as test-driven development, and how to use it in your projects.
The difference between &#8220;normal&#8221; and test-driven development (TDD) is that when doing TDD, you write unit tests for your new code before writing the code itself. This way you ensure good test coverage for your code, and [...]]]></description>
			<content:encoded><![CDATA[
			<p>In this post I&#8217;ll introduce the methodology known as test-driven development, and how to use it in your projects.</p>
<p>The difference between &#8220;normal&#8221; and test-driven development (TDD) is that when doing TDD, you write unit tests for your new code before writing the code itself. This way you ensure good test coverage for your code, and your code will also be more flexible and reusable, as you have to design the class interfaces for easy testing.</p>
<p><span id="more-243"></span></p>
<h3>Test-driven development basics</h3>
<p>As mentioned, the main idea is that before you write any actual application code, you write a unit test(s) which checks the code you will be writing.</p>
<p>It may initially be a bit difficult to adjust to writing the tests before any code. How do I know what to test when I don&#8217;t have any code?</p>
<p>The idea is not so difficult. Think of how you want to use the code, and write a test based on that. If you need to write a class which sums numbers, it needs a <code>sum</code> method and when passed two numbers the output is their sum.</p>
<h4>Preconditions and postconditions</h4>
<p>Another good approach is to think of <i>preconditions</i> and <i>postconditions</i>. This is something you can think of when writing unit tests in general, too.</p>
<ul>
<li>A <b>precondition</b> is something that must be true before something is done</li>
<li>A <b>postcondition</b> is something that must be true after something is done</li>
</ul>
<p>In tests we care more about the postconditions, but some things can be thought of as preconditions as well: When you create a new object, its properties must meet certain criterias, such as a collection should be empty. While this is actually a postcondition of the constructor, it may be easier to think of it as a precondition for any other operations.</p>
<h3>Writing code in a TDD manner</h3>
<p>Now it&#8217;s time to look at a simple example of writing code using TDD. We will first need some goal for our code.</p>
<p>Let&#8217;s say we&#8217;re writing a sales system and we need a class for orders. Orders need to have items in them, a recipient, order IDs etc.</p>
<p>We don&#8217;t have any code yet, and let&#8217;s keep it that way, as first we need to write tests. Let&#8217;s decide that an order must be empty and it must have no recipient when it&#8217;s created:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">class</span> OrderTest <span style="color: #000000; font-weight: bold;">extends</span> PHPUnit_Framework_TestCase <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testOrderStartsEmpty<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #0000ff;">$order</span> = <span style="color: #000000; font-weight: bold;">new</span> Order<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #000066;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$order</span>-&gt;<span style="color: #006600;">getItems</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testOrderStartsWithoutRecipient<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #0000ff;">$order</span> = <span style="color: #000000; font-weight: bold;">new</span> Order<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertNull</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$order</span>-&gt;<span style="color: #006600;">getRecipient</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Now we have tests that confirm the correct behavior of the constructor - we could say the postconditions of the constructor are that item count is 0 and recipient is null.</p>
<p>Of course, when running the above test it will fail quite miserably. We have no class, no methods, nothing. This is a good thing, as now we know that the test actually works as expected.</p>
<p>We can now write the <code>Order</code> class with the methods required by the test:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">class</span> Order <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #0000ff;">$_items</span> = <span style="color: #000066;">array</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #0000ff;">$_recipient</span> = <span style="color: #000000; font-weight: bold;">null</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> getItems<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #0000ff;">$this</span>-&gt;_items;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> getRecipient<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #0000ff;">$this</span>-&gt;_recipient;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>And now the tests we wrote pass. Congratulations, now you have written code using test-driven development!</p>
<h4>Another example</h4>
<p>Now, we need to be able to add items to our order. To keep things simple for the example, the items are just going to be strings such as <code>'Cat food'</code> or <code>'Bananas'</code>.</p>
<p>Again, let&#8217;s define the behavior of the code first, then write tests and then the actual code. We&#8217;ll add a method called <code>addItem</code>, which takes the item as its parameter. If the parameter is not valid, it&#8217;ll throw an exception.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testHasItemAfterAdding<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$order</span> = <span style="color: #000000; font-weight: bold;">new</span> Order<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertFalse</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$order</span>-&gt;<span style="color: #006600;">hasItem</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Cat food'</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #0000ff;">$order</span>-&gt;<span style="color: #006600;">addItem</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Cat food'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertTrue</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$order</span>-&gt;<span style="color: #006600;">hasItem</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Cat food'</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAddingInvalidItemThrowsException<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$order</span> = <span style="color: #000000; font-weight: bold;">new</span> Order<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    try <span style="color: #66cc66;">&#123;</span>
        <span style="color: #0000ff;">$order</span>-&gt;<span style="color: #006600;">addItem</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">''</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">fail</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Empty items are invalid'</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
    catch<span style="color: #66cc66;">&#40;</span>InvalidArgumentException <span style="color: #0000ff;">$ex</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>If we run the tests again, they should fail. Now we could write the code to make the tests pass, but I will leave that as an exercise to you.</p>
<h3>In closing</h3>
<p>Test-driven development is not as difficult as it may initially seem. You only need to adjust your thinking a bit.</p>
<p>You may notice that in our tests and code above we didn&#8217;t have good tests for some of the methods like getItems and hasItem. I left them out as it would&#8217;ve made the post unnecessarily long, but when writing actual code you would want to write tests for them as well. Because of such small helper methods, it may sometimes be a good idea if you have a class diagram or if you write empty stub methods in your code before writing the tests. This will help remind you of what methods you have to test.</p>
<p>Next time we&#8217;ll look at testing a Zend Framework application.</p>

			<a href="http://codeutopia.net/blog/2009/07/04/unit-testing-5-test-driven-development/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/07/04/unit-testing-5-test-driven-development/feed/</wfw:commentRss>
		</item>
		<item>
		<title>TankWar Online, my JavaScript based cannons game</title>
		<link>http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/</link>
		<comments>http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/#comments</comments>
		<pubDate>Tue, 30 Jun 2009 15:38:15 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[Web]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/</guid>
		<description><![CDATA[Back in late 2006 I wrote my most ambitious JavaScript/game project so far: TankWar Online, which as you may guess from the name was about tanks, shooting stuff, and it had a real-time online game mode - as far as I know, the first such ever in a JS based game.
Originally the game was made [...]]]></description>
			<content:encoded><![CDATA[
			<p>Back in late 2006 I wrote my most ambitious JavaScript/game project so far: <a href="http://codeutopia.net/projects/tankwar">TankWar Online</a>, which as you may guess from the name was about tanks, shooting stuff, and it had a real-time online game mode - as far as I know, the first such ever in a JS based game.</p>
<p>Originally the game was made for an older version of Opera 9, and only worked in it. However, I have now modified the game so it should work in most browsers (tested Firefox, Opera 9, 10). </p>
<p><a href="http://codeutopia.net/projects/tankwar/">Click here to play cross-browser version of the game</a>. The game should work for other parts than the online game mode, as the server is no longer functional.</p>
<p>Interested in hearing how the game works, such as terrain, physics and the computer AI? Keep reading!</p>
<p><span id="more-242"></span></p>
<h3>A disclaimer regarding the code</h3>
<p>If you want to go look into the code, feel free, but keep in mind I wrote this in late 2006 and the code is not really very good. It probably makes sense after you&#8217;re totally familiar with it, but even I who wrote the thing had problems finding the places I needed to modify to make it work once again.</p>
<h3>Main features of the game</h3>
<p>Let&#8217;s look at how some of the main features of the game work.</p>
<h3>Terrain</h3>
<p>The terrain in TankWar is generated randomly, based on a bunch of parameters. If you go into the map settings from the main menu, you can see and adjust these parameters.</p>
<p>The input fields in the map settings screen are actually Web Forms 2 (now <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#forms">a part of HTML5 forms</a>) elements, which still don&#8217;t seem to be supported by any other browser than Opera, even after many years. If you don&#8217;t have Opera handy, the main difference between the fields in other browsers and Opera is that in Opera, the fields get little arrows for increasing and decreasing the value.</p>
<p>The terrain generation algorithm itself is pretty simple. It takes the base height value, and then adds a number of points based on the height points value. The points&#8217; heights is randomized between the min height and max height values. Ta-dah, simple terrain generation.</p>
<h4>Destruction of terrain</h4>
<p>Another feature of the terrain is that it&#8217;s desctructible. If you fire a weapon at it, it&#8217;ll make a hole. You could even destroy the whole map if you destroyed all the ground.</p>
<p>To understand how the desctruction of the terrain works, we have to look at how the terrain itself is stored and rendered.</p>
<p>The terrain is stored as an array of points, which are converted into a canvas path. The path actually consists of the sky, and not the ground - the sky and ground are rendered by first filling the whole image with the ground color, and then using the terrain path to fill in the sky.</p>
<p>When some of the ground is destroyed, the game creates a circular path, which is then added to the terrain path. This way the destroyed areas of the ground get filled with the sky color as well, making it seem like the ground was destroyed, even though the terrain path itself remains unmodified.</p>
<h4>Terrain hit testing</h4>
<p>This is also used for testing hits on the ground: as long as a projectile (or a tank) is inside the terrain path, or inside one of the circular explosion paths, the projectile keeps moving. The hit check was performed by an Opera-specific method and a custom polygon hit checking function in the old code, as when I wrote it, there was no reliable way to detect whether a point was inside a path or not. In the new version, the hit is detected with the canvas method <code>isPointInPath</code>, which should work in all browsers with a modern canvas implementation.</p>
<h3>The physics engine</h3>
<p>The game features a simple physics engine, which simulates falling tanks and moving projectiles such as cannon shells. It also allows for wind.</p>
<p>It functions relatively simply: each &#8220;physics object&#8221; - tanks and shells - have some vectors which define their position and velocity. The engine has a constant gravity, and an optional wind (which is kind of like horizontal gravity), which affect objects when they move. The physics engine is not active until someone actually fires their cannon - it has no need to run when you take aim, so the engine was designed so it could be given a set of objects to simulate (tanks and the newly fired shell) and then it could run until all the objects are considered &#8220;dead&#8221;. Being dead simply means that each object has hit the ground, or for shells, hit a tank.</p>
<h3>Weapons</h3>
<p>Currently the game has eight weapons. Originally there were less, but I had wanted to add more interesting weapons, so the weapon system was designed to accomodate various kinds of weapons, as can be seen in the current selection.</p>
<p>The weapon system is based on the concept of a cannon and a shell (which is what cannons fire). The cannon acts as a kind of a factory for shells, defining how much damage they make, how large is their blast radius etc.</p>
<p>The system is also wired with some events such as an event for the time when a shell hits the ground. This enables the engine to have weapons like the teleport or the arty drop, which both have a special handler for the hit ground event, which moves the player&#8217;s tank and fires three more shells at the location from the sky, respectively.</p>
<p>The bomber weapon is a bit special. The weapon&#8217;s behavior is actually not intended - it&#8217;s a bug. It probably seems crazily overpowered sometimes, and I never meant it to drop an infinite stream of &#8220;bombs&#8221;, just five of them, but because of a bug it just turned out like that. I liked the unintended behavior and left it in, so it became a feature instead.</p>
<p>Some of the weapons were inspired by Worms 2, like the arty drop and teleport.</p>
<h3>Computer opponent</h3>
<p>This was one of the most interesting parts of writing the game. As I wanted to give players the possibility to play the game by themselves, I wanted it to have an AI player.</p>
<p>The game&#8217;s &#8220;player system&#8221; is quite flexible. It had to be, so that implementing a &#8220;local&#8221; player, a &#8220;network&#8221; player for online games and an &#8220;computer&#8221; player would be possible. Simply put, the players each implement a specific set of functions that are called in specific points during the game - the game itself doesn&#8217;t care much what the type of the player is, except in some special cases, and the player object itself handles things differently.</p>
<p>The computer AI is not very complex. To not give it a completely unfair advantage (and so that my head wouldn&#8217;t hurt too much because of the math involved), I didn&#8217;t give it a 100% precise aim - which would have been possible by computing where the shell will land, given the gravity, wind and required power and shooting angle. </p>
<p>Instead, the computer follows this graph (click to see a bigger image)<br />
<a href="http://codeutopia.net/projects/tankwar/tankwar_ai_diagram.PNG"><img src="http://codeutopia.net/projects/tankwar/tankwar_ai_diagram.PNG" width="550" alt="Diagram of how the AI works" /></a></p>
<p>The diagram is not 100% accurate, but that is the general idea of how the AI works. It does some small additional things, such as figuring if wind has changed.</p>
<h3>Currently defunct: Online play</h3>
<p>The coolest thing in the game no longer works: The online multiplay mode.</p>
<p>The online multiplayer mode was similar to what you can see in many PC games nowadays. It had a lobby where players could talk with each other, and a list of games which were active and joinable. It was also possible to protect your game with a password and choose a maximum amount of players.</p>
<p>There were some additional hidden features in the online lobby, such as the ability to join a custom room, a bit similar to joining channels on IRC. It also implemented some swearword filtering (schoolkids seemed to enojy abusing the chatroom during school hours) and an admin interface for getting rid of unwanted elements (which was implemented on the server and only worked for me)</p>
<p>The gameplay itself was the same, but in addition to the interface elements seen in a local game, the game showed you a chat box and the list of others in the game so you could talk with them during the game. As with local games, you could have up to eight players in a single game, which was a limitation I had chosen based on the map size - the game could have had 10, 20 or more players, but the map would&#8217;ve gotten very crowded.</p>
<h3>Online game server</h3>
<p>The server for the online play was lost in a fatal hard disk failure in 2008 or so. It was implemented in Python, using a library called Twisted to provide HTTP functionality.</p>
<p>The server received communications from clients with XMLHttpRequests, and sent responses using a Server-Sent DOM Events channel, which each client was required to open. Most of the stuff was quite normal client-server type of things - the clients would get an ID, send messages, receive responses and parse them etc.</p>
<p>There was quite much game related things to do on the server as well. While testing the game, I noticed a worrying inconsistency of where the shells landed on one PC compared to a slower PC - sometimes on slow PCs, the shells would land on completely different locations than on the fast PC. I fixed this by making each network player get synced from the server. Basically it meant that whenever a player&#8217;s turn was finished, the player&#8217;s game told the server where the shots had landed. The server would then broadcast this to all players in the game, and this way each player&#8217;s game was kept in perfect sync.</p>
<p>Sadly I no longer have the code as said, and it would be a rather big undertaking to write a new one - certainly possible, but I don&#8217;t have the time for it.</p>
<h3>Bottom line</h3>
<p>TankWar was, and maybe still is, my greatest widget. <a href="http://codeutopia.net/projects/city/">WidgetCity</a> was a large and complex project, but TankWar had a lot of special things in it and it was 100% written by me - WidgetCity shared a lot of algorithms with the original Sim City source code available online.</p>
<p>Here is <a href="http://codeutopia.net/projects/tankwar/tankwar_src.zip">the source code for TankWar</a>, if you want to take a look at it.</p>

			<a href="http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Unit testing 4: Mock objects and testing code which uses the database</title>
		<link>http://codeutopia.net/blog/2009/06/26/unit-testing-4-mock-objects-and-testing-code-which-uses-the-database/</link>
		<comments>http://codeutopia.net/blog/2009/06/26/unit-testing-4-mock-objects-and-testing-code-which-uses-the-database/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 16:13:19 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/26/unit-testing-4-mock-objects-and-testing-code-which-uses-the-database/</guid>
		<description><![CDATA[After learning to write tests and some good testing practices, it&#8217;s now time to look at mock objects.
When testing a class which needs an instance of another class to work, you do not want to depend on the other class too much. This is where mock objects come in - a mock object is a [...]]]></description>
			<content:encoded><![CDATA[
			<p>After <a href="http://codeutopia.net/blog/2009/06/17/unit-testing-3-writing-tests-for-existing-code/" title="Unit testing 3: Writing tests for existing code">learning to write tests and some good testing practices</a>, it&#8217;s now time to look at mock objects.</p>
<p>When testing a class which needs an instance of another class to work, you do not want to depend on the other class too much. This is where mock objects come in - a mock object is a &#8220;clone&#8221; of an object, which we can use to simplify our tests, by having the mock object perform assertions or by replacing some functionality of the mock with our custom functionality.</p>
<p>In this post we&#8217;ll first look at how mock objects are created and used with PHPUnit, and then we&#8217;ll take a practical example of using mocks to test code which uses the database to fetch some data.</p>
<p><span id="more-241"></span></p>
<h3>Mock basics</h3>
<p>Before we look at how PHPUnit does mocks, let&#8217;s first check out the principle of how the mocks work.</p>
<p>You can create mocks even without the fancy methods PHPUnit provides to you - by simply creating a new class which extends the class you wish to mock:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">class</span> SomeClassMock <span style="color: #000000; font-weight: bold;">extends</span> SomeClass <span style="color: #66cc66;">&#123;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>We could call that a mock object, although it&#8217;s not very useful yet. </p>
<p>Say the class which we are testing needs to call a method in SomeClass, and we want to be sure it actually gets called in our test. In this case, let&#8217;s add a variable and a method to our mock class:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">class</span> SomeClassMock <span style="color: #000000; font-weight: bold;">extends</span> SomeClass <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #0000ff;">$methodWasCalled</span> = <span style="color: #000000; font-weight: bold;">false</span>;
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> aMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">//This method should get called by the object we are testing</span>
    <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">methodWasCalled</span> = <span style="color: #000000; font-weight: bold;">true</span>;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Now, in our test, we can do something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #808080; font-style: italic;">//Just a simple example</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAMethodIsCalled<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #808080; font-style: italic;">//First, create a mock of SomeClass</span>
  <span style="color: #0000ff;">$someClass</span> = <span style="color: #000000; font-weight: bold;">new</span> SomeClassMock<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//This is the object we are testing, let's assume</span>
  <span style="color: #808080; font-style: italic;">//it takes a SomeClass instance as the parameter</span>
  <span style="color: #0000ff;">$object</span> = <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$someClass</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//Say the method in SomeClass needs to be called now</span>
  <span style="color: #0000ff;">$object</span>-&gt;<span style="color: #006600;">doSomething</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//Confirm the method was called by checking the mock's variable:</span>
  <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertTrue</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$someClass</span>-&gt;<span style="color: #006600;">methodWasCalled</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h3>Creating mock objects with PHPUnit</h3>
<p>Writing mock objects like we saw above is quite time consuming and complex. Luckily, we don&#8217;t have to actually write the mock classes ourselves, as PHPUnit provides us with a set of methods we can use to do almost any kind of mock we need. We will use the PHPUnit mocking API from now on, but it&#8217;s always useful to know how the things work behind the scenes.</p>
<p>Let&#8217;s rewrite the test with PHPUnit&#8217;s mocking API:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAMethodIsCalled<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #808080; font-style: italic;">//First, create a mock of SomeClass</span>
  <span style="color: #0000ff;">$someClass</span> = <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">getMock</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'SomeClass'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//Now we can tell the mock what we want to do:</span>
  <span style="color: #0000ff;">$someClass</span>-&gt;<span style="color: #006600;">expects</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">once</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
            -&gt;<span style="color: #006600;">method</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'aMethod'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//This is the object we are testing, let's assume</span>
  <span style="color: #808080; font-style: italic;">//it takes a SomeClass instance as the parameter</span>
  <span style="color: #0000ff;">$object</span> = <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$someClass</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//Say the method in SomeClass needs to be called now</span>
  <span style="color: #0000ff;">$object</span>-&gt;<span style="color: #006600;">doSomething</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//We don't need to do anything else - the mock object will confirm</span>
  <span style="color: #808080; font-style: italic;">//that the method was called for us.</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Doesn&#8217;t look too complex does it? Instead of writing a whole class to do a simple method-call check, we just use the <code>getMock</code> method to receive a mock-version of an object, and then we tell it what it needs to do in this test. </p>
<p>What did we do to the mock?</p>
<p>First, we call the <code>expects</code> method and pass <code>$this-&gt;once()</code> as a parameter. Then, we call <code>method</code> with <code>'aMethod'</code>. This means that the mock object &#8220;expects one method call to aMethod&#8221;. Replacing a method in the mock like this is also known as <i>stubbing</i> the method - the code in the method is replaced by a &#8220;test stub&#8221;.</p>
<p>What will happen if the method does not get called? You will get an error similar to this when you run your test:<br />
<samp><br />
1) testAMethodIsCalled(ExampleTest)<br />
Expectation failed for method name is equal to &lt;string:aMethod&gt; when invoked 1 time(s).<br />
Method was expected to be called 1 times, actually called 0 times.<br />
</samp></p>
<h3>Using mocks to test database code</h3>
<p>Now that we know our mocks, or at least enough to start with, let&#8217;s jump into some useful examples.</p>
<p>A very typical case is that you need to test code which uses the database - for example, the code might be fetching some data from the DB, or maybe inserting something. We certainly could have a testing database, but it&#8217;s much easier and simpler to work with mock objects.</p>
<h4>The example scenario</h4>
<p>Let&#8217;s say we have a class called <code>EventRepository</code> which tracks some kind of events in our application. We also have a class called <code>Event</code>, which represents a single event. We now want to write unit tests for the <code>EventRepository</code> class, but as the class accesses the database we have a dilemma.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">class</span> EventRepository <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #0000ff;">$_pdo</span>;
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #66cc66;">&#40;</span>PDO <span style="color: #0000ff;">$database</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$this</span>-&gt;_pdo = <span style="color: #0000ff;">$database</span>;
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> findById<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$sql</span> = <span style="color: #ff0000;">'SELECT * FROM events WHERE ...'</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">//Here we have some code to execute the SQL, convert</span>
    <span style="color: #808080; font-style: italic;">//the result to an Event object and then return it</span>
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #808080; font-style: italic;">/* some other methods here */</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>To test this class, we would need to use a test database. This is because the SQL queries etc. are executed inside the class and there&#8217;s nothing our test can do about it.</p>
<h4>Making the <code>EventRepository</code> testable</h4>
<p>To make this class better, and easier to test, let&#8217;s modify it to use a <a href="http://codeutopia.net/blog/2009/01/05/decoupling-models-from-the-database-data-access-object-pattern-in-php/" title="Decoupling models from the database: Data access object pattern in PHP">data access object</a>.</p>
<p>The data access object (DAO) will look something like this for our example:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">class</span> EventDao <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #0000ff;">$_pdo</span>;
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #66cc66;">&#40;</span>PDO <span style="color: #0000ff;">$pdo</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$this</span>-&gt;_pdo = <span style="color: #0000ff;">$pdo</span>;
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> findById<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$sql</span> = <span style="color: #ff0000;">'SELECT * FROM events WHERE ...'</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">//Instead of event repository, the code to execute SQL is here.</span>
    <span style="color: #808080; font-style: italic;">//We then return the row's data as an array</span>
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #808080; font-style: italic;">/* some other methods here */</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Then, the <code>EventRepository</code> is modified to use <code>EventDao</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">class</span> EventRepository <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #0000ff;">$_dao</span>;
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #66cc66;">&#40;</span>EventDao <span style="color: #0000ff;">$dao</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$this</span>-&gt;_dao = <span style="color: #0000ff;">$dao</span>;
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> findById<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$id</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$row</span> = <span style="color: #0000ff;">$this</span>-&gt;_dao-&gt;<span style="color: #006600;">findById</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$id</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">//Now we simply process $row into an Event object. No direct DB access</span>
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #808080; font-style: italic;">/* some other methods here */</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h4>Testing the thing</h4>
<p>Now we can test the class! We mock out the <code>EventDao</code> object, so the testing code for <code>EventRepository</code> will not need access to a database. </p>
<p>Let&#8217;s write a test for the <code>findById</code> method to demonstrate mocking the DAO:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testFindsCorrectEvent<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #808080; font-style: italic;">//Set up a fake database row</span>
  <span style="color: #0000ff;">$eventRow</span> = <span style="color: #000066;">array</span><span style="color: #66cc66;">&#40;</span>
    <span style="color: #ff0000;">'id'</span> =&gt; <span style="color: #cc66cc;">1</span>,
    <span style="color: #ff0000;">'name'</span> =&gt; <span style="color: #ff0000;">'Awesome event'</span>
  <span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$dao</span> = <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">getMock</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'EventDao'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//Set up the mock to return the fake row when findById is called</span>
  <span style="color: #0000ff;">$dao</span>-&gt;<span style="color: #006600;">expects</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">once</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
      -&gt;<span style="color: #006600;">method</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'findById'</span><span style="color: #66cc66;">&#41;</span>
      -&gt;<span style="color: #006600;">with</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
      -&gt;<span style="color: #006600;">will</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">returnValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$eventRow</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$repo</span> = <span style="color: #000000; font-weight: bold;">new</span> EventRepository<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$dao</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$event</span> = <span style="color: #0000ff;">$repo</span>-&gt;<span style="color: #006600;">findById</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #808080; font-style: italic;">//Confirm ID of the returned Event is correct</span>
  <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #0000ff;">$event</span>-&gt;<span style="color: #006600;">getId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Here we have some more features of the mock API - checking parameters and deciding return values.</p>
<p>Firstly, the <code>$eventRow</code> is a &#8220;fake&#8221; return value for the mocked dao. For the repository to work correctly, the dao will need to return it a value, and this is it.<br />
Expects and method in the mock set up is the same as before, but the <code>with(1)</code> and <code>will($this-&gt;returnValue($eventRow))</code> are new.</p>
<p><code>with</code> is used to tell the mocked method what parameters it expects, in this case it should be passed the event&#8217;s ID: 1. If it is not passed the value 1 when called, it will report the test as a failure.<br />
<code>will</code> is used to tell the mocked method what it should do when it gets called, and we want it to return our fake row.</p>
<p>The rest of the test sets up the repository that we are actually testing, and calls a method and asserts that the return value was correct. We didn&#8217;t go over the rest of the code in <code>findById</code>, nor did we give <code>Event</code> a <code>getId()</code> method, but just assume that there was some code in <code>findById</code> which turns the row into an <code>Event</code> object, and that <code>Event</code> has the method.</p>
<h3>Summing up and further reading</h3>
<p>Using the PHPUnit mocking API we can easily replace dependencies in our tested classes with mocks that make testing much simpler, than having to depend on the actual object itself.</p>
<p>We didn&#8217;t cover all possible mock calls, such as how to have it throw an exception. For that and more, I recommend reading the <a href="http://www.phpunit.de/manual/3.4/en/test-doubles.html">PHPUnit manual stubs and mocks chapter</a>.</p>
<p>In the next post, we&#8217;ll check out <a href="http://codeutopia.net/blog/2009/07/04/unit-testing-5-test-driven-development/">how to do test-driven or test-first style development</a></p>

			<a href="http://codeutopia.net/blog/2009/06/26/unit-testing-4-mock-objects-and-testing-code-which-uses-the-database/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/26/unit-testing-4-mock-objects-and-testing-code-which-uses-the-database/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Unit testing 3: Writing tests for existing code</title>
		<link>http://codeutopia.net/blog/2009/06/17/unit-testing-3-writing-tests-for-existing-code/</link>
		<comments>http://codeutopia.net/blog/2009/06/17/unit-testing-3-writing-tests-for-existing-code/#comments</comments>
		<pubDate>Wed, 17 Jun 2009 20:30:24 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/17/unit-testing-3-writing-tests-for-existing-code/</guid>
		<description><![CDATA[Now that you know what unit testing is and how to write and run tests, it&#8217;s time to look at writing tests in more depth.
Today we&#8217;ll take an example class and write tests for it. We&#8217;ll also introduce some common testing methodologies.

Our example class
To do some testing, we need a class to test. Conveniently, there&#8217;s [...]]]></description>
			<content:encoded><![CDATA[
			<p>Now that you know <a href="http://codeutopia.net/blog/2009/06/05/unit-testing-introduction/">what unit testing is</a> and <a href="http://codeutopia.net/blog/2009/06/10/unit-testing-part-2-writing-and-running-tests/">how to write and run tests</a>, it&#8217;s time to look at writing tests in more depth.</p>
<p>Today we&#8217;ll take an example class and write tests for it. We&#8217;ll also introduce some common testing methodologies.</p>
<p><span id="more-240"></span></p>
<h3>Our example class</h3>
<p>To do some testing, we need a class to test. Conveniently, there&#8217;s a class we can use in my svn repo: <a href="http://codeutopia.net/code/library/CU/Collection.php">CU_Collection</a> - a class which I wrote to demonstrate <a href="http://codeutopia.net/blog/2008/09/17/generic-collections-in-php/">generic collections in PHP</a>.</p>
<p>Here&#8217;s an example of how this class works:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #808080; font-style: italic;">//This collection only accepts strings</span>
<span style="color: #0000ff;">$coll</span> = <span style="color: #000000; font-weight: bold;">new</span> CU_Collection<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'string'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">//Add a string and echo it</span>
<span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'This is a string'</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000066;">echo</span> <span style="color: #0000ff;">$coll</span><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">//This will throw an InvalidArgumentException because 1000 is not a string</span>
<span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1000</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>This class isn&#8217;t very large, but it&#8217;s complex enough for us to demonstrate some testing principles on it. Now, let&#8217;s continue and start writing some tests!</p>
<h3>Writing a test</h3>
<p>Before we write the test, let&#8217;s remind ourselves of how the testcase should look:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">require_once</span> <span style="color: #ff0000;">'../../library/CU/Collection.php'</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> CU_CollectionTest <span style="color: #000000; font-weight: bold;">extends</span> PHPUnit_Framework_TestCase <span style="color: #66cc66;">&#123;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>This is the basic structure of the testcase class. Note that this time we have a require_once on top of the code. Why is this?</p>
<p>Because this code depends on the CU_Collection class, we actually need to include it to be able to test it. We are assuming that the test is located in a directory called &#8220;tests/CU/CollectionTest.php&#8221; under the main project directory, and the code for the CU_Collection class is in &#8220;library/CU/Collection.php&#8221;. You can structure your project differently if you wish.</p>
<p>There is also a way to use autoloading and include paths, but that will be discussed in a later post.</p>
<p><b>Now, let&#8217;s write that test</b>. If you look at the code of the class, you can see it should start with an empty collection with no items in it. Let&#8217;s write a test for it:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">require_once</span> <span style="color: #ff0000;">'../../library/CU/Collection.php'</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> CU_CollectionTest <span style="color: #000000; font-weight: bold;">extends</span> PHPUnit_Framework_TestCase <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testCollectionStartsEmpty<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$coll</span> = <span style="color: #000000; font-weight: bold;">new</span> CU_Collection<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'string'</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #000066;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$coll</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>It may seem very simple at this point. Don&#8217;t worry, writing unit tests usually <i>is</i> this simple! Let&#8217;s look at some more examples next&#8230;</p>
<h3>Testing code vs. testing behavior</h3>
<p>As I mentioned in <a href="http://codeutopia.net/blog/2009/06/05/unit-testing-introduction/">the introduction post</a>, a good unit test checks the expected behavior of some code, not that the code does what it looks like it&#8217;s doing if you read it line by line.</p>
<p>Let&#8217;s write a test for the add method:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #808080; font-style: italic;">//this code again goes inside the CU_CollectionTest class</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAdding<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #0000ff;">$coll</span> = <span style="color: #000000; font-weight: bold;">new</span> CU_Collection<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'string'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'foobar'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #000066;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$coll</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  try <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">fail</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Should throw exception'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
  catch<span style="color: #66cc66;">&#40;</span>InvalidArgumentException <span style="color: #0000ff;">$ex</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Trying to add a value of wrong type'</span>, <span style="color: #0000ff;">$ex</span>-&gt;<span style="color: #006600;">getMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Is this a good test? It looks correct, and when you run it, it passes with flying colors. However, in a sense, this is <i>not</i> a good test!</p>
<p>The problem of this test is that it&#8217;s strictly written in the fashion &#8220;Okay, looks like the code does this, so let&#8217;s test that it does that&#8221;. While this test can be helpful, it would be better to rewrite it as we&#8217;ll see next. Also, consider the fact that the code you&#8217;re writing the test for could have a bug! If it was a more complex method than the one in this case, it could very well corrupt your test as a result if you don&#8217;t notice it.</p>
<p>Now, before writing the test, let&#8217;s consider what behaviors we expect from the add method:</p>
<ol>
<li>If we add a correct type, the length of the collection should increase</li>
<li>If we add an incorrect type, we should get an InvalidArgumentException</li>
</ol>
<p>So for this parts, the initial test was quite correct. It is good to keep in mind that you should always consider the behaviors, and only test one behavior per test, as we will do now. Sometimes you can see such behaviors from just the phpdoc comments without reading the code itself, but when writing tests for existing code you will often need to look at the code to find them.</p>
<p>First, let&#8217;s test the behavior #1:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAddingCorrectType<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #0000ff;">$coll</span> = <span style="color: #000000; font-weight: bold;">new</span> CU_Collection<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'string'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'foobar'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #000066;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$coll</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>And the second behavior:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAddingWrongTypeCausesException<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #0000ff;">$coll</span> = <span style="color: #000000; font-weight: bold;">new</span> CU_Collection<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'string'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  try <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">fail</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Should throw exception'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
  catch<span style="color: #66cc66;">&#40;</span>InvalidArgumentException <span style="color: #0000ff;">$ex</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Note here that the assertion which checked the exception&#8217;s message was removed. In this case, I think it&#8217;s enough that we test that the exception thrown is of the expected type. The content of the exception&#8217;s message itself is not so important. </p>
<h3>Fixing bugs</h3>
<p>Often you will want to write a unit test when you encounter a bug, to be sure that the bug will not reappear in the future. This is called <a href="http://en.wikipedia.org/wiki/Regression_testing">regression testing</a>, and I think it&#8217;s very important in longer running projects, or frameworks such as the Zend Framework.</p>
<p>This brings us to another thing that can help improve your tests:</p>
<p><b>A test should initially result in a failure.</b></p>
<p><br/><br />
This doesn&#8217;t mean you need to write an incorrect test, or intentionally break your code. It means that when writing a test for a bug, or when doing test-driven development, you should write your test before writing the actual code.</p>
<p>Let&#8217;s introduce a bug into the CU_Collection class so that we can demonstrate this.</p>
<p>Modify the remove method&#8217;s array_splice call to not define the amount of items to remove. An easy mistake to make, but it can be difficult to spot!</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> remove<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$index</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
  <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$index</span> &gt;= <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    throw <span style="color: #000000; font-weight: bold;">new</span> OutOfRangeException<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Index out of range'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #000066;">array_splice</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$this</span>-&gt;_collection, <span style="color: #0000ff;">$index</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//Uh oh!</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Remember that array_splice&#8217;s third parameter is the amount of items to remove, and if left undefined, it will remove everything in the array from that index onwards!</p>
<p>A naive unit test which checks only that remove works won&#8217;t do, such as this one:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testRemovingItem<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #0000ff;">$coll</span> = <span style="color: #000000; font-weight: bold;">new</span> CU_Collection<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'string'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'foobar'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #000066;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$coll</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Even though we introduced a bug, this one will still pass. Imagine if you fixed the bug, and then wrote this to test against it? Oops. Don&#8217;t get me wrong, this is an okay test, but it won&#8217;t help us this time.</p>
<p>We need a better test:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testRemovingItemFromTheMiddle<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #0000ff;">$coll</span> = <span style="color: #000000; font-weight: bold;">new</span> CU_Collection<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'string'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'one'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'two'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'three'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$coll</span>-&gt;<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #000066;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$coll</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>If we run the testcase against the broken code, this test will fail. Now we know that the test for our bug works, and we can then proceed to fix the bug. After fixing the bug, the test passes.</p>
<h3>Conclusion</h3>
<p>Now you should be able to write good tests yourself. Test behaviors, and fail first!</p>
<p>Do you have any burning questions? Feel free to any in the comments!</p>
<p>Next week in unit testing we&#8217;ll look into mock objects, which are necessary when testing more complex classes. Continue to <a href="http://codeutopia.net/blog/2009/06/26/unit-testing-4-mock-objects-and-testing-code-which-uses-the-database/">Unit testing 4: Mock objects and testing code which uses the database</a></p>

			<a href="http://codeutopia.net/blog/2009/06/17/unit-testing-3-writing-tests-for-existing-code/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/17/unit-testing-3-writing-tests-for-existing-code/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How WidgetCity does a tile-based map using just CSS</title>
		<link>http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/</link>
		<comments>http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 12:38:18 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/</guid>
		<description><![CDATA[My city building game, WidgetCity, displays the city as a table, each cell of a table representing one tile.
The tile map is done purely using just CSS, and CSS classes. The map is also scrollable.
How is this all done?

Multiple approaches
As always, there is more than one approach to doing this type of a tile map.
The [...]]]></description>
			<content:encoded><![CDATA[
			<p>My city building game, <a href="http://codeutopia.net/projects/city/">WidgetCity</a>, displays the city as a table, each cell of a table representing one tile.</p>
<p>The tile map is done purely using just CSS, and CSS classes. The map is also scrollable.</p>
<p>How is this all done?</p>
<p><span id="more-239"></span></p>
<h3>Multiple approaches</h3>
<p>As always, there is more than one approach to doing this type of a tile map.</p>
<p>The most obvious approach is to chop down each graphic in the game to one tile sized small images. Then, each of the small images is applied using a background image to each of the tiles. For example, an industrial zone is 3&#215;3 tiles, so this would need 9 small images which each get applied to specific tiles to build the whole industrial zone.</p>
<p>This small image approach can be done in two ways: Using a CSS style to put the image as the background, or by inserting an img tag into the cell and changing its src.</p>
<p>There&#8217;s a lot of different graphics for just a single type of zone: Indstrial zones for example have different graphics for different land valued zones and different populations on the zone. The above approach would work, but it would require a lot of work to chop each big graphic into small ones and also each image would have to follow a specific naming scheme so it could be applied correctly.</p>
<p>Another approach is similar to what is used in <a href="http://www.alistapart.com/articles/sprites">CSS sprites</a>: Each larger graphic is contained in a single file, and the image is then mapped into the small cells using CSS&#8217; background-position.</p>
<h3>The chosen approach</h3>
<p>I decided to use the approach similar to CSS sprites. This is because it was simpler to work with the files, as I didn&#8217;t need to rename all the little images and define tons of CSS classes just to apply the specific backgrounds. This also somewhat simplified the JavaScript code applying the styles.</p>
<p>The game defines a set of CSS naming rules which are used in the stylesheets, so the code in the game can easily apply styles without having to use special cases all over the place. Each cell&#8217;s className attribute consists of several classes:</p>
<ul class="biggerMargins">
<li>An &#8220;offset class&#8221;, which is used to place the big image into the small cell: for example, &#8220;o31&#215;1&#8243; is the bottom right corner of a 3&#215;3 tile - o for offset, 3 for 3&#215;3, 1&#215;1 for the X and Y offset from the center of the tile. The game knows which position of the tile it&#8217;s laying out, so it simply adds the respective offset class into the cell&#8217;s className.</li>
<li>The main &#8220;graphic class&#8221;, such as &#8220;indbuilding&#8221; for an industrial building.</li>
<li>A &#8220;land value/population class&#8221;. This is used to choose which graphic of the building to actually display, such as a small rowhouse, or a big skyscraper. These look like v0p1, where v0 means land value 0 and p1 means population 1</li>
</ul>
<p>There are also some other special classes:</p>
<ul>
<li>nopower class is applied to zone center cells if the zone doesn&#8217;t have power. This shows the little no power indicator</li>
<li>For roads and powerlines, there are classes called up, right, down and left, which are applied in following cases: if you have a road, and there&#8217;s a section of road above it, the class &#8220;up&#8221; is given to the bottom road cell, and the class &#8220;down&#8221; is given to the upper. If there&#8217;s also a road to the left of the upper cell, it gets &#8220;left&#8221;. In the stylesheet, there are combinations of these four classes, which apply the correct road and powerline graphics to the cells.</li>
</ul>
<h3>The scripting side of things</h3>
<p>Of course all this won&#8217;t work without JavaScript. Behind the scenes, the game stores the map as a two dimensional array of objects. The objects in the array contain various data, which is used to determine which classes to apply to each cell when &#8220;rendering&#8221; the map.</p>
<p>The classes are also applied only when something changes - the game keeps track of what classes are in the cells, as re-applying the class incurs a performance penalty.</p>
<h3>What about canvas?</h3>
<p>Lastly, some words on an alternative to using a table: the HTML5 canvas element.</p>
<p>While it may seem &#8220;wrong&#8221; to use table to do something like this, I think it&#8217;s in certain ways better than canvas. Firstly, you get better performance, and second, you need less code.</p>
<p>Using canvas, you would need to write the code to draw the correct parts of the graphics, and if you wanted animations like the game has now, you would need to write timing code to run the animations. So in addition to the performance penalty of using canvas rendering, you would need additional JavaScript code running the animations and everything else.</p>
<p>The benefits of using canvas would be that you could provide smooth scrolling. With a table it would be very tricky if not completely unfeasible. Canvas would also allow zooming or other effects.</p>

			<a href="http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Unit testing part 2: Writing and running tests</title>
		<link>http://codeutopia.net/blog/2009/06/10/unit-testing-part-2-writing-and-running-tests/</link>
		<comments>http://codeutopia.net/blog/2009/06/10/unit-testing-part-2-writing-and-running-tests/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 11:44:53 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/10/unit-testing-part-2-writing-and-running-tests/</guid>
		<description><![CDATA[Continuing from the unit test introduction, we will now continue and take a look at how to write tests and ways to run the tests.

Setting up PHPUnit
Before we can write tests, we need a testing tool. We are going to use PHPUnit for our examples, so you will need to install it.
The easiest way to [...]]]></description>
			<content:encoded><![CDATA[
			<p>Continuing from <a href="http://codeutopia.net/blog/2009/06/05/unit-testing-introduction/">the unit test introduction</a>, we will now continue and take a look at how to write tests and ways to run the tests.</p>
<p><span id="more-238"></span></p>
<h3>Setting up PHPUnit</h3>
<p>Before we can write tests, we need a testing tool. We are going to use PHPUnit for our examples, so you will need to install it.</p>
<p>The easiest way to install it is through PEAR. Read <a href="http://www.phpunit.de/manual/current/en/installation.html">the PHPUnit installation guide</a> for information on how to do that.</p>
<p>You will also need to be able to run PHP on the command line, including the phpunit command-line script. If you&#8217;re on Linux, chances are you already have PHP available on the command line - if not, the package for installing command-line PHP is usually something like php5-cli or such.</p>
<p>I have previously written a post on <a href="http://codeutopia.net/blog/2008/07/28/setting-up-command-line-php-on-windows/">setting up command-line PHP on windows</a>, which you can read to make it work on Windows.</p>
<p>To confirm everything works as expected, run a shell or command prompt and type in:</p>
<pre><kbd>phpunit --version</kbd></pre>
<p>which should output something like this:</p>
<pre><samp>PHPUnit 3.3.17 by Sebastian Bergmann.</samp></pre>
<h3>Using PHPUnit</h3>
<p>Next, let&#8217;s take a look at how to use PHPUnit so that we know how to use it when we actually start writing some real tests.</p>
<h4>Writing a testcase</h4>
<p>PHPUnit tests are written as testcase classes, which extend <code>PHPUnit_Framework_TestCase</code>. Let&#8217;s take a simple example to show you how they work.<br />
For this example, we will just write a quick test for PHP&#8217;s array and count function.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">class</span> ArrayTest <span style="color: #000000; font-weight: bold;">extends</span> PHPUnit_Framework_TestCase <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> testAddingItemsIncreasesLength<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$array</span> = <span style="color: #000066;">array</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #0000ff;">$expectedLength</span> = <span style="color: #000066;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$array</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #cc66cc;">1</span>;
&nbsp;
    <span style="color: #0000ff;">$array</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #ff0000;">'foo'</span>;
    <span style="color: #0000ff;">$this</span>-&gt;<span style="color: #006600;">assertEquals</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$expectedLength</span>, <span style="color: #000066;">count</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$array</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #ff0000;">'Length was not correct'</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>  
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>As you can see from the code here, our test class is called <code>ArrayTest</code> and it extends from the PHPUnit testcase class. The naming convention for classes such as this is usually <code>ClassNameTest</code> - for example, a testcase for <code>Zend_Controller_Action</code> would be called <code>Zend_Controller_ActionTest</code>.</p>
<p>The ArrayTest class contains one method: <code>testAddingItemsIncreasesLength</code>. This is a test method. The convention for PHPUnit is that test methods are named <code>testDescriptionOfWhatIsTested</code>, so since our test checks that when we add an item into the array, the count is increased by one, our test is called <code>testAddingItemsIncreasesLength</code>. You can write as many test methods in a testcase as you think is necessary.</p>
<p>The code in the test method should be quite easy to understand - we create an array, calculate what the expected length of the array should be, push an item into the array and finally we have an assertion that confirms the result is as we expected. You can find <a href="http://www.phpunit.de/manual/current/en/api.html">a list of assertions you can do in the PHPUnit manual</a>.</p>
<h4>Running tests</h4>
<p>Now that we have a test, how do we run it? These are the usual ways to do it:</p>
<ol class="biggerMargins">
<li>The most straightforward way is to run a single testcase with phpunit, like this: <kbd>phpunit NameOfTest</kbd>, so to run our ArrayTest, we can do <kbd>phpunit ArrayTest</kbd>. Note that this assumes you are in the directory where the test is saved, and that the filename is ArrayTest.php.</li>
<li>Writing a test suite. This is complex and annoying to maintain, so I won&#8217;t go into it any more. If you really want to know, there&#8217;s <a href="http://www.phpunit.de/manual/current/en/organizing-tests.html#organizing-tests.testsuite">a chapter on it in the PHPUnit manual</a>.</li>
<li>Using an XML configuration file. This is the easiest way to run multiple tests, so we&#8217;ll take a look at writing this next.</li>
</ol>
<p>Since most of the time you&#8217;ll want to run all of your tests, or you have more than one test that you want to run, doing it manually with <kbd>phpunit SomeTest</kbd> isn&#8217;t very feasible. Option #2 can be used to run multiple tests in one go, but as said, it&#8217;s not exactly a very good method.</p>
<p>So to run multiple tests, we&#8217;ll use method #3 - an XML configuration file. This file can be named whatever you want, but it&#8217;s probably a good idea to call it <kbd>phpunit.xml</kbd> because that means phpunit will detect it automatically.</p>
<p>Here&#8217;s an example phpunit.xml configuration file:</p>

<div class="wp_syntax"><div class="code"><pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;phpunit<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;testsuite</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Test suite name&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;directory<span style="font-weight: bold; color: black;">&gt;</span></span></span>path/to/tests<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/directory<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/testsuite<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/phpunit<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre></div></div>

<p>This is the simplest possible xml configuration. All we define is a testsuite element with a name attribute, and a path to the tests. </p>
<p>The typical directory layout for tests is like this:</p>
<pre>
project/tests
project/tests/phpunit.xml
project/tests/App/SomeClassTest.php (this is a test for class App_SomeClass)
</pre>
<p>In this case, you would set the directory in the phpunit.xml file to . to tell it the tests are in the current dir, like this:</p>

<div class="wp_syntax"><div class="code"><pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;phpunit<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;testsuite</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;My tests&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;directory<span style="font-weight: bold; color: black;">&gt;</span></span></span>.<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/directory<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/testsuite<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/phpunit<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre></div></div>

<p>Using this kind of a configuration file, we can now easily run all our tests by just typing <kbd>phpunit</kbd> on the command-line, and phpunit will then read the config and execute all tests, providing us with feedback about the process.</p>
<p>The configuration file has other options you can add to it too. We won&#8217;t look at other properties in this post, but you can find <a href="http://www.phpunit.de/manual/current/en/appendixes.configuration.html">a list of configuration options from the PHPUnit manual</a>.</p>
<h3>Next week&#8217;s post</h3>
<p>Next week we will <i>finally</i> get to actually writing some tests for some example methods. We&#8217;ll take a look at a class or two, and look at how to write good tests for it: <a href="http://codeutopia.net/blog/2009/06/17/unit-testing-3-writing-tests-for-existing-code/">Unit testing 3: writing tests for existing code</a></p>
<p>I&#8217;d like to apologize to those of you who were waiting for that to show up in this week&#8217;s post - I kind of forgot that explaining how to run tests and all that would need it&#8217;s own post, and posting that before going any further made more sense.</p>

			<a href="http://codeutopia.net/blog/2009/06/10/unit-testing-part-2-writing-and-running-tests/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/10/unit-testing-part-2-writing-and-running-tests/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Refactoring</title>
		<link>http://codeutopia.net/blog/2009/06/08/refactoring/</link>
		<comments>http://codeutopia.net/blog/2009/06/08/refactoring/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 06:14:58 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/08/refactoring/</guid>
		<description><![CDATA[Today I&#8217;d like to point out a bunch of good articles about refactoring - the process of improving code without changing the functionality. 
Sameer Borate has written four posts about the topic in his blog, and I encourage you to check them out:

Refactoring: An introduction to PHP programmers
Refactoring 1: Conslidate conditional expressions
Refactoring 2: Extract method
Refactoring [...]]]></description>
			<content:encoded><![CDATA[
			<p>Today I&#8217;d like to point out a bunch of good articles about refactoring - the process of improving code without changing the functionality. </p>
<p>Sameer Borate has written four posts about the topic in his blog, and I encourage you to check them out:</p>
<ul>
<li><a href="http://www.codediesel.com/refactoring/introduction-to-refactoring-in-php/">Refactoring: An introduction to PHP programmers</a></li>
<li><a href="http://www.codediesel.com/php/refactoring-1-consolidate-conditional-expression/">Refactoring 1: Conslidate conditional expressions</a></li>
<li><a href="http://www.codediesel.com/refactoring/refactoring-2-extract-method/">Refactoring 2: Extract method</a></li>
<li><a href="http://www.codediesel.com/refactoring/refactoring-3-replace-temp-with-query/">Refactoring 3: Replace temp with query</a></li>
</ul>

			<a href="http://codeutopia.net/blog/2009/06/08/refactoring/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/08/refactoring/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Unit testing: Introduction</title>
		<link>http://codeutopia.net/blog/2009/06/05/unit-testing-introduction/</link>
		<comments>http://codeutopia.net/blog/2009/06/05/unit-testing-introduction/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 18:43:01 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/05/unit-testing-introduction/</guid>
		<description><![CDATA[Due to popular demand, I&#8217;ll be writing a bunch of posts on unit testing.
In this post I&#8217;ll introduce unit testing: What it is, when it&#8217;s a good idea and when it might not be. I&#8217;ll also discuss a bit about what makes for a good unit test.
Next week I&#8217;ll post a followup to this, which [...]]]></description>
			<content:encoded><![CDATA[
			<p>Due to <a href="http://codeutopia.net/blog/2009/06/02/what-would-you-like-to-read-about-on-codeutopia/">popular demand</a>, I&#8217;ll be writing a bunch of posts on unit testing.</p>
<p>In this post I&#8217;ll introduce unit testing: What it is, when it&#8217;s a good idea and when it might not be. I&#8217;ll also discuss a bit about what makes for a good unit test.</p>
<p>Next week I&#8217;ll post a followup to this, which will be more about actually writing unit tests with examples.</p>
<p><span id="more-236"></span></p>
<h3>What is unit testing</h3>
<p>If you are already familiar with the concept, you may wish to skip this chapter.</p>
<p>Simply put, unit testing means writing code to test other code. There are a variety of libraries for testing for various languages: for PHP there are PHPUnit and SimpleTest, for Java there&#8217;s JUnit, NUnit for .NET Framework languages, etc.</p>
<p>The idea is that when you write tests for your code using one of these tools, you can easily automate them and run them as often as needed. By writing unit tests, you can easily ensure that your code works as expected, even if the code is later changed, as your tests stay the same and you can (and should) always run them after doing changes.</p>
<p>There&#8217;s a good <a href="http://en.wikipedia.org/wiki/Unit_testing">article on unit testing in wikipedia</a>, which you should check out for a more in-depth explanation of it.</p>
<h3>When is unit testing a good idea?</h3>
<p>There&#8217;s a short answer to this: Always.</p>
<p>And there&#8217;s also a long answer to this: It depends on how complex your project is, and how long is its estimated lifetime.</p>
<p>If you have a very simple project, writing unit tests for it may take time that would be better spent in just writing the project itself. If it&#8217;s simple, it&#8217;s less likely to be difficult to test and it&#8217;ll be easier to find errors by manually using it.</p>
<p>If your project&#8217;s estimated lifetime is short, you may again want to not spend time writing tests. If the lifetime is short, you usually won&#8217;t have to maintain it or do any changes to the code, making unit tests less beneficial.</p>
<p>That being said, if you have the time and resources to write unit tests for even small/short projects, it may be a good idea. It largely depends on the situation, and you should make the call based on your specific circumstances, but the two cases I mentioned should serve as good examples.</p>
<h3>Writing good unit tests</h3>
<p>The idea of a unit test is to <b>test the behavior</b> of a piece of code. This is usually a class and some method of it.</p>
<p>When writing tests, you usually would want to write one test per behavior: Expected behavior of code when given correct values and expected behavior of code when given incorrect values are the essential ones you will want to write. Depending on the case, there may be more tests that you&#8217;ll want to write, but these two are good ones to start with.</p>
<p>A common metric for determining how good a set of unit tests are is <i>code coverage</i>. Code coverage is determined by checking how much of the total code your unit tests execute - does each if and else block get executed by some test, does every function get called, etc.</p>
<p>While code coverage is a quite good metric, it can be misleading. Even if your tests cover 100% of your code, they may not actually test each behavior correctly. </p>
<p>I&#8217;ll show you some examples of good tests and testing behaviors next week.</p>
<h3>In closing</h3>
<p>Unit testing is a great way to improve code quality - correctness, but also modularity, because it forces you to write code in a way that it&#8217;s reusable and flexible, as it would otherwise be difficult to test.</p>
<p>In <a href="http://codeutopia.net/blog/2009/06/10/unit-testing-part-2-writing-and-running-tests/">the next part</a> we will take a more hands-on coding approach and I&#8217;ll show you some practical examples of writing unit tests.</p>

			<a href="http://codeutopia.net/blog/2009/06/05/unit-testing-introduction/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/05/unit-testing-introduction/feed/</wfw:commentRss>
		</item>
		<item>
		<title>What would you like to read about on CodeUtopia?</title>
		<link>http://codeutopia.net/blog/2009/06/02/what-would-you-like-to-read-about-on-codeutopia/</link>
		<comments>http://codeutopia.net/blog/2009/06/02/what-would-you-like-to-read-about-on-codeutopia/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 21:07:18 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[general]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/02/what-would-you-like-to-read-about-on-codeutopia/</guid>
		<description><![CDATA[I haven&#8217;t had much ideas to write about lately, so how about this: You, my dear readers, get to tell me your favorite topic that you&#8217;d like to read/learn about.
Is there a specific topic you would like me to write about? As long as it&#8217;s somewhat relevant to this blog&#8217;s past content, post your idea [...]]]></description>
			<content:encoded><![CDATA[
			<p>I haven&#8217;t had much ideas to write about lately, so how about this: You, my dear readers, get to tell me your favorite topic that you&#8217;d like to read/learn about.</p>
<p>Is there a specific topic you would like me to write about? As long as it&#8217;s somewhat relevant to this blog&#8217;s past content, post your idea to the comments! - I just might pick <i>your</i> idea and write about it. I even might pick more than one.</p>
<p>It doesn&#8217;t matter if it&#8217;s a small thing or a large thing. If it&#8217;s interesting, it&#8217;s good! It can be a general topic, like Zend Framework or design patterns, or some more specific thing like &#8220;how to do X&#8221;</p>

			<a href="http://codeutopia.net/blog/2009/06/02/what-would-you-like-to-read-about-on-codeutopia/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/02/what-would-you-like-to-read-about-on-codeutopia/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Should I try Git if Svn/CVS/other works for me?</title>
		<link>http://codeutopia.net/blog/2009/06/01/should-i-try-git-if-svncvsother-works-for-me/</link>
		<comments>http://codeutopia.net/blog/2009/06/01/should-i-try-git-if-svncvsother-works-for-me/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 16:22:22 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
		
		<category><![CDATA[general]]></category>

		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/01/should-i-try-git-if-svncvsother-works-for-me/</guid>
		<description><![CDATA[I&#8217;ve been using Subversion for quite a while, and while it has some minor annoyances like complex merging, it never really bothered me.
Then along comes Git, touting that it&#8217;s easy and that you&#8217;re stupid if you don&#8217;t use it. The technical stuff people said about it were impressing, but not enough to actually warrant trying [...]]]></description>
			<content:encoded><![CDATA[
			<p>I&#8217;ve been using Subversion for quite a while, and while it has some minor annoyances like complex merging, it never really bothered me.</p>
<p>Then along comes Git, touting that it&#8217;s easy and that you&#8217;re stupid if you don&#8217;t use it. The technical stuff people said about it were impressing, but not enough to actually warrant trying it for me - Afterall, I was quite happy with svn, as it did what I needed.</p>
<p>After a while, I decided I wanted to try Git anyway - just out of curiosity, to see if it actually was so amazingly much better. And in this post I&#8217;ll tell you if it was</p>
<p><span id="more-234"></span></p>
<h3>Basics</h3>
<p>I&#8217;ve been using Git for a while now with some small projects - nothing very large, so bear that in mind: some Git features are probably more useful with bigger stuff.</p>
<p>The main functionality of Git is pretty similar to what Subversion has, git add, git commit, etc. - of course there are some minor semantic differences, and then there&#8217;s the whole local/remote repository concept.</p>
<p>Overall, I think Git is as easy to use as svn is, and there is also a GUI which makes certain tasks simpler.</p>
<p>Feature-wise in my testing I&#8217;ve found that while some features in Git are convenient, it doesn&#8217;t really have any major advantages over svn in my use. However, <i>I still prefer it over svn</i>.</p>
<h3>Why Git over Svn?</h3>
<p>There&#8217;s a lot of stuff on the net on what makes Git better than some other version control system, such as <a href="http://whygitisbetterthanx.com/">Why Git is better than X</a>, which is good for an overview of Git&#8217;s features vs. some others.</p>
<p>Here are some reasons that I&#8217;d like to add, as many sites only list the technical aspects:</p>
<ol>
<li>You can commit only specific lines. I often modify some files, adding more than one feature. I might have a bunch of files and only one of the features is complete, so I don&#8217;t want to include the modifications related to the incomplete one in the commit. With Git, I can choose only the lines that are relevant to the commit, and include those.</li>
<li>You can modify the commit, for example if you forgot to include a file in the commit, you won&#8217;t need to make a new commit for it. I often forget to include a file in a commit, so I keep making additional commits with the forgotten files - and I don&#8217;t like that.</li>
<li>It&#8217;s fast</li>
<li>You can &#8220;stash&#8221; your work - put your modifications away to a safe place and reset the files to the latest revision, and you can later get the modifications back easily</li>
</ol>
<h3>So should you try it?</h3>
<p>Yes! Absolutely. I wasn&#8217;t convinced by just reading other people&#8217;s opinions about it as they never quite covered the things that I appreciate about Git now that I have tried it, so you too should definitely try it as it has a lot of useful features.</p>
<p>It may not be amazing enough to warrant moving all your existing repositories over to it right away, but I think it&#8217;s still worth giving a shot - who knows, maybe you have use-cases that I don&#8217;t, where Git can help you become more productive.</p>

			<a href="http://codeutopia.net/blog/2009/06/01/should-i-try-git-if-svncvsother-works-for-me/#comments">Post a comment</a>
		]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/01/should-i-try-git-if-svncvsother-works-for-me/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
