<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Ad-Hockery]]></title>
  <link href="http://blog.freeside.co/atom.xml" rel="self"/>
  <link href="http://blog.freeside.co/"/>
  <updated>2012-05-09T01:49:11+01:00</updated>
  <id>http://blog.freeside.co/</id>
  <author>
    <name><![CDATA[Rob Fletcher]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Testing with embedded Vert.x]]></title>
    <link href="http://blog.freeside.co/blog/2012/05/09/testing-with-embedded-vertx/"/>
    <updated>2012-05-09T00:47:00+01:00</updated>
    <id>http://blog.freeside.co/blog/2012/05/09/testing-with-embedded-vertx</id>
    <content type="html"><![CDATA[<p>I blogged recently about <a href="http://blog.freeside.co/blog/2012/05/01/using-spock-mocks-to-test-callbacks/">using Spock to test APIs that use callbacks</a>. The post came out of some work I&#8217;ve been doing with <a href="http://vertx.io/">Vert.x</a>. Although the tests I wrote worked, I found them rather mock-heavy and felt I wasn&#8217;t using the Vert.x API as idiomatically as I could have been.</p>

<p>Next I tried <a href="http://vertx.io/manual.html#vertx-embedded">creating an embedded <code>Vertx</code> instance</a> in my test and sending messages to my component over the real event bus. This is surprisingly easy and worked well.</p>

<!--more-->


<p>The embedded API doesn&#8217;t allow you to deploy <em>verticles</em> or start <a href="http://vertx.io/manual.html#busmods">busmods</a> as they are intended to run in isolated classloaders. You <em>can</em> use the event bus, though.</p>

<p>For example consider the following component that handles event bus messages and looks up documents using Vert.x&#8217;s <a href="http://vertx.io/mods_manual.html#mongodb-persistor">Mongo DB persistor</a>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kd">class</span> <span class="nc">MyComponent</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">EventBus</span> <span class="n">eventBus</span>
</span><span class='line'>
</span><span class='line'>    <span class="kt">void</span> <span class="nf">read</span><span class="o">(</span><span class="n">Message</span> <span class="n">message</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">eventBus</span><span class="o">.</span><span class="na">send</span><span class="o">(</span><span class="s1">&#39;mongo.persistor&#39;</span><span class="o">,</span> <span class="o">[</span><span class="nl">action:</span> <span class="s1">&#39;find-one&#39;</span><span class="o">,</span> <span class="nl">matcher:</span> <span class="o">[</span><span class="nl">id:</span> <span class="n">message</span><span class="o">.</span><span class="na">body</span><span class="o">.</span><span class="na">id</span><span class="o">]])</span> <span class="o">{</span> <span class="n">reply</span> <span class="o">-&gt;</span>
</span><span class='line'>            <span class="k">if</span> <span class="o">(</span><span class="n">reply</span><span class="o">.</span><span class="na">body</span><span class="o">.</span><span class="na">status</span> <span class="o">==</span> <span class="s1">&#39;ok&#39;</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>                <span class="k">if</span> <span class="o">(</span><span class="n">reply</span><span class="o">.</span><span class="na">body</span><span class="o">.</span><span class="na">results</span><span class="o">)</span> <span class="n">message</span><span class="o">.</span><span class="na">reply</span> <span class="nl">status:</span> <span class="s1">&#39;found&#39;</span><span class="o">,</span> <span class="nl">title:</span> <span class="n">reply</span><span class="o">.</span><span class="na">body</span><span class="o">.</span><span class="na">results</span><span class="o">[</span><span class="mi">0</span><span class="o">].</span><span class="na">title</span>
</span><span class='line'>                <span class="k">else</span> <span class="n">message</span><span class="o">.</span><span class="na">reply</span> <span class="nl">status:</span> <span class="s1">&#39;not-found&#39;</span>
</span><span class='line'>            <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span><span class='line'>                <span class="n">message</span><span class="o">.</span><span class="na">reply</span> <span class="nl">status:</span> <span class="s1">&#39;error&#39;</span><span class="o">,</span> <span class="nl">message:</span> <span class="s1">&#39;o noes something went wrong&#39;</span>
</span><span class='line'>            <span class="o">}</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>To test this first I initialized the Vert.x instance and registered my component as a handler on the event bus. I&#8217;m waiting until Vert.x calls back to indicate that the handler is registered successfully then storing the handler&#8217;s <em>id</em> so that I can easily clean it up after the test:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="nd">@Shared</span> <span class="kt">def</span> <span class="n">vertx</span> <span class="o">=</span> <span class="n">Vertx</span><span class="o">.</span><span class="na">newVertx</span><span class="o">()</span>
</span><span class='line'><span class="kt">def</span> <span class="n">component</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MyComponent</span><span class="o">(</span><span class="nl">eventBus:</span> <span class="n">vertx</span><span class="o">.</span><span class="na">eventBus</span><span class="o">)</span>
</span><span class='line'><span class="kt">def</span> <span class="n">handlerIds</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Stack</span><span class="o">()</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="nf">setup</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">registerHandler</span> <span class="s1">&#39;my.component&#39;</span><span class="o">,</span> <span class="n">component</span><span class="o">.&amp;</span><span class="n">read</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">private</span> <span class="kt">void</span> <span class="nf">registerHandler</span><span class="o">(</span><span class="n">String</span> <span class="n">address</span><span class="o">,</span> <span class="n">Closure</span> <span class="n">handler</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="kt">def</span> <span class="n">readyLatch</span> <span class="o">=</span> <span class="k">new</span> <span class="n">CountDownLatch</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span>
</span><span class='line'>    <span class="n">handlerIds</span> <span class="o">&lt;&lt;</span> <span class="n">vertx</span><span class="o">.</span><span class="na">eventBus</span><span class="o">.</span><span class="na">registerHandler</span><span class="o">(</span><span class="n">address</span><span class="o">,</span> <span class="n">handler</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">readyLatch</span><span class="o">.</span><span class="na">countDown</span><span class="o">()</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>    <span class="k">assert</span> <span class="n">readyLatch</span><span class="o">.</span><span class="na">await</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="n">SECONDS</span><span class="o">)</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="nf">cleanup</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">while</span> <span class="o">(!</span><span class="n">handlerIds</span><span class="o">.</span><span class="na">empty</span><span class="o">())</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">vertx</span><span class="o">.</span><span class="na">eventBus</span><span class="o">.</span><span class="na">unregisterSimpleHandler</span> <span class="n">handlerIds</span><span class="o">.</span><span class="na">pop</span><span class="o">()</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Vert.x&#8217;s Groovy API uses closures for all handlers on the event bus so I&#8217;ve used <a href="http://mrhaki.blogspot.co.uk/2009/08/groovy-goodness-turn-methods-into.html">Groovy&#8217;s <code>.&amp;</code> operator</a> to turn the method on my component into a closure.</p>

<p>Then I added a <a href="https://code.google.com/p/spock/wiki/Interactions">Spock Mock</a> to represent the Mongo DB persistor that my component will send messages to. This also needs to be registered on the event bus:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">def</span> <span class="n">persistor</span> <span class="o">=</span> <span class="n">Mock</span><span class="o">(</span><span class="n">Handler</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="nf">setup</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="c1">// ...</span>
</span><span class='line'>    <span class="n">registerHandler</span> <span class="s1">&#39;mongo.persistor&#39;</span><span class="o">,</span> <span class="n">persistor</span><span class="o">.&amp;</span><span class="n">handle</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Finally, a feature method to test what happens when the requested document does not exist in the Mongo DB datastore:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">void</span> <span class="s1">&#39;read calls back with not-found status if there is nothing in the database&#39;</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="nl">given:</span>
</span><span class='line'>    <span class="n">persistor</span><span class="o">.</span><span class="na">handle</span><span class="o">(</span><span class="n">_</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="o">{</span> <span class="n">Message</span> <span class="n">message</span> <span class="o">-&gt;</span>
</span><span class='line'>        <span class="n">message</span><span class="o">.</span><span class="na">reply</span> <span class="nl">status:</span> <span class="s1">&#39;ok&#39;</span><span class="o">,</span> <span class="nl">results:</span> <span class="o">[]</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="nl">and:</span>
</span><span class='line'>    <span class="kt">def</span> <span class="n">reply</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BlockingVariable</span><span class="o">&lt;</span><span class="n">Message</span><span class="o">&gt;()</span>
</span><span class='line'>
</span><span class='line'>    <span class="nl">when:</span>
</span><span class='line'>    <span class="n">vertx</span><span class="o">.</span><span class="na">eventBus</span><span class="o">.</span><span class="na">send</span><span class="o">(</span><span class="s1">&#39;my.component&#39;</span><span class="o">,</span> <span class="o">[</span><span class="nl">id:</span> <span class="s1">&#39;1234&#39;</span><span class="o">])</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">reply</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="n">it</span><span class="o">)</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="nl">then:</span>
</span><span class='line'>    <span class="n">reply</span><span class="o">.</span><span class="na">get</span><span class="o">().</span><span class="na">body</span><span class="o">.</span><span class="na">status</span> <span class="o">==</span> <span class="s1">&#39;not-found&#39;</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The mock persistor executes its own callback. Realistically I&#8217;d want to use a better matcher for the persistor mock there, but I&#8217;ve used a wildcard for simplicity in the example. Note that the <code>reply</code> spy is an instance of <code>spock.util.concurrent.BlockingVariable</code> as I need to ensure the assertion blocks until the callback is actually executed.</p>

<p>This is fine for scenarios where I&#8217;m validating the component&#8217;s interaction with the persistor. For more complex tests for things like data integrity I&#8217;m going to need to figure out a way to wire up real collaborators like the Mongo persistor rather than using a mock. If I figure out a neat way of doing so I&#8217;ll post again.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Testing callbacks with Spock mocks]]></title>
    <link href="http://blog.freeside.co/blog/2012/05/01/testing-callbacks-with-spock-mocks/"/>
    <updated>2012-05-01T12:50:00+01:00</updated>
    <id>http://blog.freeside.co/blog/2012/05/01/testing-callbacks-with-spock-mocks</id>
    <content type="html"><![CDATA[<p>I&#8217;ve been doing some work with <a href="http://vertx.io/">vert.x</a> over the last few days and trying to develop components that are test-driven. Like any asynchronous framework rather than having methods that return a value you pass a callback Closure that gets invoked at some point in the future with the result. This makes it tricky to write unit tests that mock out collaborators as you might in a traditional app.</p>

<!--more-->


<p>For example, a simple REST server that saves some data might make a call like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">void</span> <span class="nf">post</span><span class="o">(</span><span class="n">request</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="kt">def</span> <span class="n">album</span> <span class="o">=</span> <span class="o">[</span><span class="nl">artist:</span> <span class="n">request</span><span class="o">.</span><span class="na">params</span><span class="o">.</span><span class="na">artist</span><span class="o">,</span> <span class="nl">title:</span> <span class="n">request</span><span class="o">.</span><span class="na">params</span><span class="o">.</span><span class="na">title</span><span class="o">]</span>
</span><span class='line'>    <span class="n">eventBus</span><span class="o">.</span><span class="na">send</span><span class="o">(</span><span class="s1">&#39;mongodb&#39;</span><span class="o">,</span> <span class="o">[</span><span class="nl">action:</span> <span class="s1">&#39;save&#39;</span><span class="o">,</span> <span class="nl">collection:</span> <span class="s1">&#39;albums&#39;</span><span class="o">,</span> <span class="nl">document:</span> <span class="n">album</span><span class="o">])</span> <span class="o">{</span> <span class="n">reply</span> <span class="o">-&gt;</span>
</span><span class='line'>        <span class="k">if</span> <span class="o">(</span><span class="n">reply</span><span class="o">.</span><span class="na">body</span><span class="o">.</span><span class="na">status</span> <span class="o">==</span> <span class="s1">&#39;ok&#39;</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>          <span class="n">request</span><span class="o">.</span><span class="na">response</span><span class="o">.</span><span class="na">statusCode</span> <span class="o">=</span> <span class="mi">200</span>
</span><span class='line'>          <span class="n">request</span><span class="o">.</span><span class="na">response</span><span class="o">.</span><span class="na">end</span> <span class="s1">&#39;Updated OK&#39;</span>
</span><span class='line'>        <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span><span class='line'>          <span class="n">request</span><span class="o">.</span><span class="na">response</span><span class="o">.</span><span class="na">statusCode</span> <span class="o">=</span> <span class="mi">500</span>
</span><span class='line'>          <span class="n">request</span><span class="o">.</span><span class="na">response</span><span class="o">.</span><span class="na">end</span> <span class="s2">&quot;Update failed: $reply.body.message&quot;</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The the Closure passed to <code>eventBus.send</code> will be called once the <em>save</em> action has been completed and depending on the result the correct HTTP status and message will get returned to the client.</p>

<p>In a unit test we might want to use a mock <em>eventBus</em> but we&#8217;re not calling a method that returns a value; how do we get the mock to invoke the callback? It&#8217;s not a well documented feature but using a <a href="http://code.google.com/p/spock/wiki/Interactions"><em>Spock</em> mock</a> you can get to the arguments passed to a mocked method using a Closure like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">void</span> <span class="s1">&#39;the server returns HTTP_OK if the save succeeds&#39;</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="nl">given:</span>
</span><span class='line'>    <span class="n">server</span><span class="o">.</span><span class="na">eventBus</span> <span class="o">=</span> <span class="n">Mock</span><span class="o">(</span><span class="n">EventBus</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nl">when:</span> <span class="s1">&#39;the server gets invoked&#39;</span>
</span><span class='line'>    <span class="c1">// for this example let&#39;s assume the request has been set up</span>
</span><span class='line'>    <span class="n">server</span><span class="o">.</span><span class="na">post</span><span class="o">(</span><span class="n">request</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nl">then:</span> <span class="s1">&#39;the save is executed&#39;</span>
</span><span class='line'>    <span class="mi">1</span> <span class="o">*</span> <span class="n">server</span><span class="o">.</span><span class="na">eventBus</span><span class="o">.</span><span class="na">send</span><span class="o">(</span><span class="n">_</span><span class="o">,</span> <span class="n">_</span><span class="o">,</span> <span class="n">_</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="o">{</span> <span class="n">address</span><span class="o">,</span> <span class="n">params</span><span class="o">,</span> <span class="n">callback</span> <span class="o">-&gt;</span>
</span><span class='line'>      <span class="n">callback</span><span class="o">([</span><span class="nl">body:</span> <span class="o">[</span><span class="nl">status:</span> <span class="s1">&#39;ok&#39;</span><span class="o">]])</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="nl">and:</span> <span class="s1">&#39;HTTP_OK is returned to the client&#39;</span>
</span><span class='line'>    <span class="n">request</span><span class="o">.</span><span class="na">response</span><span class="o">.</span><span class="na">statusCode</span> <span class="o">==</span> <span class="mi">200</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>In a real test you&#8217;d want to use stricter matching on the mock interaction, but using Spock&#8217;s <code>_</code> wildcard for the final callback parameter is the right thing to do.</p>

<p>What about testing a method that accepts a callback Closure directly? I&#8217;ve found that using a mock works fine there too. Imagine we&#8217;re writing a test for this method:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">void</span> <span class="nf">parse</span><span class="o">(</span><span class="n">input</span><span class="o">,</span> <span class="n">Closure</span> <span class="n">callback</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">try</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// do some complex processing</span>
</span><span class='line'>      <span class="n">callback</span><span class="o">(</span><span class="nl">status:</span> <span class="s1">&#39;ok&#39;</span><span class="o">,</span> <span class="nl">result:</span> <span class="n">output</span><span class="o">)</span>
</span><span class='line'>    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="n">callback</span><span class="o">(</span><span class="nl">status:</span> <span class="s1">&#39;error&#39;</span><span class="o">)</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>It does some work and then invokes a callback. How can we test that the parameters passed to the callback Closure are correct?</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">void</span> <span class="s1">&#39;callback is invoked with parse output&#39;</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="nl">given:</span>
</span><span class='line'>    <span class="kt">def</span> <span class="n">callback</span> <span class="o">=</span> <span class="n">Mock</span><span class="o">(</span><span class="n">Closure</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nl">when:</span>
</span><span class='line'>    <span class="n">parser</span><span class="o">.</span><span class="na">parse</span><span class="o">(</span><span class="s1">&#39;my input data&#39;</span><span class="o">,</span> <span class="n">callback</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nl">then:</span>
</span><span class='line'>    <span class="mi">1</span> <span class="o">*</span> <span class="n">callback</span><span class="o">.</span><span class="na">call</span><span class="o">([</span><span class="nl">status:</span> <span class="s1">&#39;ok&#39;</span><span class="o">,</span> <span class="nl">result:</span> <span class="s1">&#39;my expected output&#39;</span><span class="o">])</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This works pretty well. The only downside is that if <code>callback</code> is called with the wrong arguments or not called at all you get the same output in your test results:</p>

<pre><code>Too few invocations for:

1 * callback.call([status: 'ok', result: 'my expected output'])   (0 invocations)
</code></pre>

<p>For more helpful output you can use a Closure to trap the arguments passed to the callback like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="nl">then:</span>
</span><span class='line'><span class="mi">1</span> <span class="o">*</span> <span class="n">callback</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">_</span><span class="o">)</span> <span class="o">&gt;&gt;</span> <span class="o">{</span> <span class="n">args</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="k">assert</span> <span class="n">args</span><span class="o">[</span><span class="mi">0</span><span class="o">].</span><span class="na">status</span> <span class="o">==</span> <span class="s1">&#39;ok&#39;</span>
</span><span class='line'>  <span class="k">assert</span> <span class="n">args</span><span class="o">[</span><span class="mi">0</span><span class="o">].</span><span class="na">result</span> <span class="o">==</span> <span class="s1">&#39;my expected output&#39;</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Spock Killer Features: The 'old' method]]></title>
    <link href="http://blog.freeside.co/blog/2012/02/15/spock-killer-features-the-old-method/"/>
    <updated>2012-02-15T06:46:00+00:00</updated>
    <id>http://blog.freeside.co/blog/2012/02/15/spock-killer-features-the-old-method</id>
    <content type="html"><![CDATA[<p>I use Spock almost exclusively to test Groovy or Java code these days. It&#8217;s got some fantastic features that other test frameworks don&#8217;t have. Some of them aren&#8217;t that well known or documented, though.</p>

<p>The <code>old</code> method is possibly my favourite Spock feature. It&#8217;s a simple thing but really enhances test legibility. It&#8217;s also great for wowing developers new to Spock because it looks like black magic at first glance.</p>

<!--more-->


<p>Consider a simple test like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="nl">when:</span>
</span><span class='line'><span class="n">myList</span> <span class="o">&lt;&lt;</span> <span class="s1">&#39;foo&#39;</span>
</span><span class='line'>
</span><span class='line'><span class="nl">then:</span>
</span><span class='line'><span class="n">myList</span><span class="o">.</span><span class="na">size</span><span class="o">()</span> <span class="o">==</span> <span class="mi">1</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is fine in simple cases, but what happens if <code>myList.size()</code> is in a less predictable state? I&#8217;ve used this technique for testing cache usage for instance; making assertions about hit &amp; miss counts and cache size. Those numbers are less predictable as they&#8217;ll be affected by other things (concurrency or side-effects of test setup, for example). Hardcoding expected values makes the tests brittle.</p>

<p>We can improve things a little by comparing the value after the <code>when:</code> block with the value before it:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="nl">given:</span>
</span><span class='line'><span class="kt">def</span> <span class="n">oldSize</span> <span class="o">=</span> <span class="n">myList</span><span class="o">.</span><span class="na">size</span><span class="o">()</span>
</span><span class='line'>
</span><span class='line'><span class="nl">when:</span>
</span><span class='line'><span class="n">myList</span> <span class="o">&lt;&lt;</span> <span class="s1">&#39;foo&#39;</span>
</span><span class='line'>
</span><span class='line'><span class="nl">then:</span>
</span><span class='line'><span class="n">myList</span><span class="o">.</span><span class="na">size</span><span class="o">()</span> <span class="o">==</span> <span class="n">oldSize</span> <span class="o">+</span> <span class="mi">1</span>
</span></code></pre></td></tr></table></div></figure>


<p>With Spock&#8217;s <code>old</code> method there&#8217;s an even neater way, though:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="nl">when:</span>
</span><span class='line'><span class="n">myList</span> <span class="o">&lt;&lt;</span> <span class="s1">&#39;foo&#39;</span>
</span><span class='line'>
</span><span class='line'><span class="nl">then:</span>
</span><span class='line'><span class="n">myList</span><span class="o">.</span><span class="na">size</span><span class="o">()</span> <span class="o">==</span> <span class="n">old</span><span class="o">(</span><span class="n">myList</span><span class="o">.</span><span class="na">size</span><span class="o">())</span> <span class="o">+</span> <span class="mi">1</span>
</span></code></pre></td></tr></table></div></figure>


<p>Wait, WTF is going on there? That&#8217;s voodoo!</p>

<p>In fact Spock is using an AST transformation to execute the call to <code>old</code> <em>before</em> the <code>when:</code> block. If you step through the spec with the debugger in IntelliJ Idea you&#8217;ll see exactly what&#8217;s going on. The execution jumps to the line with <code>old</code> before the <code>when:</code> block lines, then visits it again afterwards.</p>

<p>The <code>old</code> method returns the value an arbitrary statement had <em>before</em> the preceding <code>when:</code> block was executed. Because of this <code>old</code> can only be used in a <code>then:</code> block (or any subsequent <code>and:</code> blocks).</p>

<p>There&#8217;s no limit to what you can do with <code>old</code>. I&#8217;ve used it in <em>Geb</em> specs to do things like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="nl">given:</span>
</span><span class='line'><span class="n">to</span> <span class="n">CocktailListPage</span>
</span><span class='line'>
</span><span class='line'><span class="nl">when:</span>
</span><span class='line'><span class="n">to</span> <span class="n">NewCocktailPage</span>
</span><span class='line'><span class="n">cocktail</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="s1">&#39;Dirty Martini&#39;</span>
</span><span class='line'><span class="n">cocktail</span><span class="o">.</span><span class="na">save</span><span class="o">.</span><span class="na">click</span><span class="o">()</span>
</span><span class='line'>
</span><span class='line'><span class="nl">then:</span>
</span><span class='line'><span class="n">at</span> <span class="n">CocktailListPage</span>
</span><span class='line'>
</span><span class='line'><span class="nl">and:</span>
</span><span class='line'><span class="n">cocktailList</span><span class="o">.</span><span class="na">names</span> <span class="o">==</span> <span class="n">old</span><span class="o">(</span><span class="n">cocktailList</span><span class="o">.</span><span class="na">names</span><span class="o">)</span> <span class="o">+</span> <span class="o">[</span><span class="s1">&#39;Dirty Martini&#39;</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Semi-RESTful Scaffolded Controllers]]></title>
    <link href="http://blog.freeside.co/blog/2012/02/07/semi-restful-scaffolded-controllers/"/>
    <updated>2012-02-07T10:56:00+00:00</updated>
    <id>http://blog.freeside.co/blog/2012/02/07/semi-restful-scaffolded-controllers</id>
    <content type="html"><![CDATA[<p>The default Grails scaffolded controllers use a <em>create</em> action to render a form and a <em>save</em> action as the target the form will <em>POST</em> to. If the <em>save</em> action succeeds it redirects to <em>show</em> and if it fails due to constraint violations it re-renders the form. The same applies to editing with the <em>edit</em> and <em>update</em> actions.</p>

<p>There&#8217;s a slight quirk here in that a failed <em>save</em> will cause the URL to change from <em>/controllerName/create</em> to <em>/controllerName/save</em>. Not a particularly huge issue, after all it&#8217;s not something a search spider will see and users will be very unlikely to care. One thing I have found problematic though is when rendering a navigation element that highlights an item based on the current action.</p>

<!--more-->


<p>Imagine a bit of GSP code like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;nav&gt;</span>
</span><span class='line'>  <span class="nt">&lt;g:link</span> <span class="na">action=</span><span class="s">&quot;list&quot;</span> <span class="na">class=</span><span class="s">&quot;${actionName == &#39;list&#39; ? &#39;active&#39; : &#39;&#39;}&quot;</span><span class="nt">&gt;</span>List Cocktails<span class="nt">&lt;/g:link&gt;</span>
</span><span class='line'>  <span class="nt">&lt;g:link</span> <span class="na">action=</span><span class="s">&quot;create&quot;</span> <span class="na">class=</span><span class="s">&quot;${actionName == &#39;create&#39; ? &#39;active&#39; : &#39;&#39;}&quot;</span><span class="nt">&gt;</span>Create Cocktail<span class="nt">&lt;/g:link&gt;</span>
</span><span class='line'>  <span class="nt">&lt;g:link</span> <span class="na">action=</span><span class="s">&quot;search&quot;</span> <span class="na">class=</span><span class="s">&quot;${actionName == &#39;search&#39; ? &#39;active&#39; : &#39;&#39;}&quot;</span><span class="nt">&gt;</span>Search Cocktails<span class="nt">&lt;/g:link&gt;</span>
</span><span class='line'><span class="nt">&lt;/nav&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>This creates a navigation element with links to the various controller actions &amp; highlights the current action. However, if we&#8217;ve submitted bad data from the <em>create</em> form no navigation element will be highlighted. With scaffolding this is easy to fix by changing the test to <code>actionName in ['create', 'save']</code> but with custom controllers the relationship between actions might not always be so predictable and the navigation template will need frequent tweaking to stay up to date as the code evolves.</p>

<p>With the <a href="http://grails-twitter-bootstrap.cloudfoundry.com">Twitter Bootstrap scaffolding example</a> I created recently I used a different pattern in the scaffolded controller template:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">def</span> <span class="nf">create</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">switch</span> <span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">method</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">case</span> <span class="s1">&#39;GET&#39;</span><span class="o">:</span>
</span><span class='line'>      <span class="c1">// render the form</span>
</span><span class='line'>  <span class="k">case</span> <span class="s1">&#39;POST&#39;</span><span class="o">:</span>
</span><span class='line'>      <span class="c1">// save the object</span>
</span><span class='line'>      <span class="c1">// if successful redirect</span>
</span><span class='line'>      <span class="c1">// otherwise re-render the form</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Effectively I&#8217;ve merged the <em>create</em> and <em>save</em> actions. The form posts back to the <em>create</em> action instead of <em>save</em>. This means the URL only changes when we successfully redirect away from creating our object &amp; the <em>create</em> navigation entry stays highlighted if we screw up creating our object.</p>

<p>I&#8217;ve done the same with the <em>edit</em> and <em>update</em> actions. Have a look at <a href="https://github.com/robfletcher/twitter-bootstrap-scaffolding/blob/master/src/templates/scaffolding/Controller.groovy#L16">the full source on GitHub</a> if you&#8217;re interested.</p>

<p>It feels like a step closer to a RESTful interface. I&#8217;m using the HTTP verbs to determine what to do with requests to the same URL. Full RESTful mapping isn&#8217;t possible as forms will only <em>GET</em> or <em>POST</em> not <em>PUT</em> or <em>DELETE</em>. Also using <a href="http://grails.org/doc/latest/guide/theWebLayer.html#mappingHTTP">Grails&#8217; RESTful URL mappings</a> would defeat the point as the action name in the GSP would be different.</p>

<p>This is neat enough but a couple of objections occur:</p>

<ul>
<li>I don&#8217;t particularly like the switch statement, but controller actions should be kept trivial anyway (controllers are for routing requests around, not performing complex logic).</li>
<li>Unit testing becomes marginally more awkward as we have to set <code>request.method</code> rather than just invoking a different action.</li>
<li>This is a sledgehammer to crack a nut &amp; only a pedant would care. Yeah, fair enough.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Twitter Bootstrap & Semantics]]></title>
    <link href="http://blog.freeside.co/blog/2012/02/02/twitter-bootstrap-and-semantics/"/>
    <updated>2012-02-02T11:07:00+00:00</updated>
    <id>http://blog.freeside.co/blog/2012/02/02/twitter-bootstrap-and-semantics</id>
    <content type="html"><![CDATA[<p>There&#8217;s a lot to like about <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a>; it&#8217;s a fantastic resource for getting off the ground, particularly for getting a slick-looking admin interface up and running quickly. The recent changes to accommodate responsive layouts are really impressive. I&#8217;m particularly impressed with the way <a href="http://twitter.github.com/bootstrap/base-css.html#forms">horizontal forms</a> stack on smaller screens (failure to accommodate small screens in form design is something I&#8217;ve <a href="https://twitter.com/#!/rfletcherEW/status/161718223207804928">complained about before</a>). However, there are some things I&#8217;m less keen on…</p>

<!--more-->


<p>Looking at the markup it seems heavy and overly concerned with presentation. In <a href="http://twitter.github.com/bootstrap/examples/fluid.html">this example layout</a> links in the top navbar have no less than 4 <em>divs</em> between them and the top of the document. There are a lot of classes everywhere and almost all of them are concerned with presentation rather than semantics; <em>how</em> a <em>div</em> should look rather than what it represents. Classes like <code>row-fluid</code>, <code>span9</code> even the ubiquitous <code>btn</code> are slightly troubling as they&#8217;re bleeding presentation details into the markup.</p>

<p>I get that these are to some extent practical considerations. Restyling all <code>button</code> elements would be disruptive for people who wanted to drop Bootstrap in to an existing site, for example. Maybe I&#8217;m being pedantic but I&#8217;ve worked on sites with severe div-itis and it makes things difficult both for maintenance and accommodating changes.</p>

<p>I can&#8217;t help thinking that this…</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>  <span class="nt">&lt;/div&gt;</span><span class="c">&lt;!--/span--&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span><span class="c">&lt;!--/row--&gt;</span>
</span><span class='line'>  <span class="nt">&lt;/div&gt;</span><span class="c">&lt;!--/span--&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span><span class="c">&lt;!--/row--&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>…is a code smell.</p>

<p>Bootstrap is built with <em><a href="http://lesscss.org/">LESS</a></em> but (by default) compiles it down to CSS before any of your site&#8217;s code starts interacting with the Bootstrap framework.</p>

<p><em>LESS</em> is great for structuring CSS better but I think its strengths go further.</p>

<p>I recently came across <em><a href="http://semantic.gs/">The Semantic Grid System</a></em> which really leverages the power of <em>LESS</em> (or <em><a href="http://sass-lang.com/">SASS</a></em> or <em><a href="http://learnboost.github.com/stylus/">Stylus</a></em> if you prefer) . The <em>semantic.gs</em> provides mixins that you use on the components of your pages. It&#8217;s a full-blown responsive grid system with not a <code>column-container</code>, <code>row</code> or <code>grid-8</code> class anywhere in your markup. In fact, looking at the markup you wouldn&#8217;t know the content was being laid out on a grid. It&#8217;s all handled in your <em>LESS</em> file. Want your <em>services</em> and <em>clients</em> sections laid out as &#8532; width blocks with your <em>about me</em> section as a sidebar? Just declare:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="nt">section</span><span class="nf">#services</span><span class="o">,</span> <span class="nt">section</span><span class="nf">#clients</span> <span class="p">{</span>
</span><span class='line'>    <span class="o">.</span><span class="n">column</span><span class="p">(</span><span class="m">9</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nt">aside</span><span class="nf">#about-me</span> <span class="p">{</span>
</span><span class='line'>    <span class="o">.</span><span class="n">column</span><span class="p">(</span><span class="m">3</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Instead of adding a presentational class to elements in the markup you add a mixin to the element in the <em>LESS</em> file.</p>

<p>Wait a minute… Isn&#8217;t that dangerously close to the separation of semantics and presentation that the invention of CSS promised us all those years ago?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[optional tag bodies]]></title>
    <link href="http://blog.freeside.co/blog/2012/01/10/optional-tag-bodies/"/>
    <updated>2012-01-10T19:56:00+00:00</updated>
    <id>http://blog.freeside.co/blog/2012/01/10/optional-tag-bodies</id>
    <content type="html"><![CDATA[<p>Sometimes you may want to implement a Grails GSP tag that has an optional body. Grails tag closures take one or two arguments, the first a map of the attributes passed to the tag the second a <em>Closure</em> representing the tag body. Even if the tag was not invoked with a body the second argument is not <em>null</em> so doing this does not work:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">def</span> <span class="n">myTag</span> <span class="o">=</span> <span class="o">{</span> <span class="n">attrs</span><span class="o">,</span> <span class="n">body</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="k">if</span> <span class="o">(!</span><span class="n">body</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// render a default body</span>
</span><span class='line'>  <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// render the supplied tag body</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>It turns out that if the tag did not have a body the argument passed to the <em>Closure</em> is always the same constant, so what you <em>can</em> do is:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kn">import</span> <span class="nn">org.codehaus.groovy.grails.web.pages.GroovyPage</span>
</span><span class='line'>
</span><span class='line'><span class="kt">def</span> <span class="n">myTag</span> <span class="o">=</span> <span class="o">{</span> <span class="n">attrs</span><span class="o">,</span> <span class="n">body</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="k">if</span> <span class="o">(</span><span class="n">body</span><span class="o">.</span><span class="na">is</span><span class="o">(</span><span class="n">GroovyPage</span><span class="o">.</span><span class="na">EMPTY_BODY_CLOSURE</span><span class="o">))</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// render a default body</span>
</span><span class='line'>  <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// render the supplied tag body</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Wiring taglib dependencies in Grails 2 unit tests]]></title>
    <link href="http://blog.freeside.co/blog/2011/12/23/wiring-taglib-dependencies-in-unit-tests/"/>
    <updated>2011-12-23T10:24:00+00:00</updated>
    <id>http://blog.freeside.co/blog/2011/12/23/wiring-taglib-dependencies-in-unit-tests</id>
    <content type="html"><![CDATA[<p>Grails 2 has made a lot of improvements in unit testing support. One of the things I always used to find particularly painful was unit testing taglibs. Now when your test class is annotated with <code>@TestFor(MyTagLib)</code> you can use the <code>applyTemplate</code> method like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="nl">expect:</span>
</span><span class='line'><span class="n">applyTemplate</span><span class="o">(</span><span class="s1">&#39;&lt;my:tag/&gt;&#39;</span><span class="o">)</span> <span class="o">==</span> <span class="s1">&#39;the expected output&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>However, one thing I found is that it&#8217;s quite tricky to wire a dependency in to the taglib instance that&#8217;s used by the <code>applyTemplate</code> method.</p>

<!--more-->


<p>Let&#8217;s imagine that <code>my:tag</code> makes a call to a Grails service for some reason. In the tag&#8217;s unit test you&#8217;ll need to wire in a mock or real instance of that service.</p>

<p>Although like with the old <code>TagLibUnitTest</code> and <code>TagLibSpec</code> classes your test gets a field called <code>taglib</code> that doesn&#8217;t actually appear to be the instance that <code>applyTemplate</code> uses. This fails:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">void</span> <span class="nf">setup</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">tagLib</span><span class="o">.</span><span class="na">myService</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MyService</span><span class="o">()</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="s1">&#39;a taglib spec&#39;</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="nl">expect:</span>
</span><span class='line'>  <span class="n">applyTemplate</span><span class="o">(</span><span class="s1">&#39;&lt;my:tag/&gt;&#39;</span><span class="o">)</span> <span class="o">==</span> <span class="s1">&#39;the expected output&#39;</span>
</span><span class='line'>  <span class="c1">// blows up with NullPointerException when the tag tries to call the service</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Grails 2 unit test mixins provide a <code>defineBeans</code> method that allows you to add Spring beans to a mock application context using the <em>BeanBuilder</em> DSL. So, next I tried this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">void</span> <span class="nf">setup</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">defineBeans</span> <span class="o">{</span>
</span><span class='line'>      <span class="n">myService</span><span class="o">(</span><span class="n">MyService</span><span class="o">)</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="s1">&#39;a taglib spec&#39;</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="nl">expect:</span>
</span><span class='line'>  <span class="n">applyTemplate</span><span class="o">(</span><span class="s1">&#39;&lt;my:tag/&gt;&#39;</span><span class="o">)</span> <span class="o">==</span> <span class="s1">&#39;the expected output&#39;</span>
</span><span class='line'>  <span class="c1">// blows up with NullPointerException when the tag tries to call the service</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>After some digging I discovered that you need to use <code>defineBeans</code> in <code>setupSpec</code> rather than <code>setup</code> for the wiring to work (I guess this would mean in <code>@BeforeClass</code> in a JUnit test). So this <em>does</em> work:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">void</span> <span class="nf">setupSpec</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">defineBeans</span> <span class="o">{</span>
</span><span class='line'>      <span class="n">myService</span><span class="o">(</span><span class="n">MyService</span><span class="o">)</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="s1">&#39;a taglib spec&#39;</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="nl">expect:</span>
</span><span class='line'>  <span class="n">applyTemplate</span><span class="o">(</span><span class="s1">&#39;&lt;my:tag/&gt;&#39;</span><span class="o">)</span> <span class="o">==</span> <span class="s1">&#39;the expected output&#39;</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>All very well so long as you don&#8217;t need to inject a specific instance of <em>MyService</em> into the tag. Unfortunately, often you will need to do exactly that so that you can wire in a stub or mock that your test can control. Also, Spock&#8217;s mocks can&#8217;t be created in <code>setupSpec</code> only in <code>setup</code> or the specification methods.</p>

<p>The test does get an <code>applicationContext</code> variable, but that doesn&#8217;t have a method on its API to allow you to register an existing object as a bean. Spring&#8217;s <code>MockApplicationContext</code> does, and after some digging I found that there&#8217;s an instance of that available as <code>grailsApplication.mainContext</code>. However a bean added there doesn&#8217;t get picked up by the tag either:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">def</span> <span class="n">mockService</span> <span class="o">=</span> <span class="n">Mock</span><span class="o">(</span><span class="n">MyService</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="nf">setup</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">grailsApplication</span><span class="o">.</span><span class="na">mainContext</span><span class="o">.</span><span class="na">registerBean</span><span class="o">(</span><span class="s1">&#39;myService&#39;</span><span class="o">,</span> <span class="n">mockService</span><span class="o">)</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="s1">&#39;a taglib spec&#39;</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="nl">expect:</span>
</span><span class='line'>  <span class="n">applyTemplate</span><span class="o">(</span><span class="s1">&#39;&lt;my:tag/&gt;&#39;</span><span class="o">)</span> <span class="o">==</span> <span class="s1">&#39;the expected output&#39;</span>
</span><span class='line'>  <span class="c1">// still blows up with NullPointerException when the tag tries to call the service</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Eventually I figured out that instead of registering your mock dependency in the application context you can instead get the correct taglib instance <em>from</em> the application context and then wire its dependencies directly. I use Spock&#8217;s mocks almost exclusively for this kind of thing, but the same technique should hold for any other mocking framework. What I ended up doing is this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kt">def</span> <span class="n">mockService</span> <span class="o">=</span> <span class="n">Mock</span><span class="o">(</span><span class="n">MyService</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="nf">setup</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="kt">def</span> <span class="n">taglib</span> <span class="o">=</span> <span class="n">applicationContext</span><span class="o">.</span><span class="na">getBean</span><span class="o">(</span><span class="n">MyTagLib</span><span class="o">)</span>
</span><span class='line'>  <span class="n">taglib</span><span class="o">.</span><span class="na">myService</span> <span class="o">=</span> <span class="n">mockService</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="s1">&#39;a taglib spec&#39;</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="nl">expect:</span>
</span><span class='line'>  <span class="n">applyTemplate</span><span class="o">(</span><span class="s1">&#39;&lt;my:tag/&gt;&#39;</span><span class="o">)</span> <span class="o">==</span> <span class="s1">&#39;the expected output&#39;</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Hopefully this is something that will get ironed out in a future Grails release but in the meantime hopefully this will be helpful for anyone who gets as stumped as I did.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Organizing functional tests]]></title>
    <link href="http://blog.freeside.co/blog/2011/11/30/organizing-functional-tests/"/>
    <updated>2011-11-30T23:27:00+00:00</updated>
    <id>http://blog.freeside.co/blog/2011/11/30/organizing-functional-tests</id>
    <content type="html"><![CDATA[<p>I posted a few days ago <a href="http://adhockery.blogspot.com/2011/11/fear-loathing-in-functional-testing.html">about functional testing &amp; some of my frustrations</a>, focusing mainly on the technical issues. I did touch on test organization in terms of modelling behaviour rather than page structure. As <a href="http://ldaley.com/post/13251886270/in-response-to-robs-post-on-functional-testing">Luke Daley has pointed out</a> the two aren&#8217;t fundamentally in opposition and I&#8217;ve been giving this some further thought.</p>

<p>I think the crux of the issue is that functional tests, end-to-end tests, acceptance tests, whatever you want to call them are <em>not</em> the same thing as unit tests. They&#8217;re not really even just a higher level of the same thing. Yet on the projects I&#8217;ve worked on we&#8217;ve generally carried on as though they were.</p>

<p>Unit tests are associated almost on a one-to-one basis with units of code. When you execute <code>grails create-controller Foo</code> the framework generates a skeleton controller and a unit test for it. You certainly shouldn&#8217;t be slavishly beholden to the one unit test class per production class habit but it&#8217;s generally reasonable. Each unit test describes the behaviour of a single unit of the software. I don&#8217;t think the same association <em>is</em> appropriate for functional tests but we often end up using it anyway.</p>

<p>I&#8217;ve tried to distil some rules of thumb from all this.</p>

<!--more-->


<h2>1: Organize tests around features not units of code</h2>

<p>When it comes to writing functional tests in Java or Groovy the tendency is to follow the pattern of associating tests to some kind of unit of software. Typically it&#8217;s a test per web page or significant page component (e.g. <em>ArticlePageSpec</em>, <em>NewsTickerSpec</em>). When dealing with the content management side of apps rather than the public facing it often defaults to a test per high level domain object.</p>

<p>When work is started on new functionality the temptation is often to augment existing tests rather than creating new ones. Oh, this card deals with <em>article</em> pages on the site so let&#8217;s go find the <em>ArticlePageSpec</em> and add our coverage there.</p>

<p>The functional tests are supposed to be, among other things, the living, executable documentation for your product. So there should be a strong association between the tests and the features that have been implemented over the life of the project. In the teams I&#8217;ve worked on features have been tracked using index cards on a board but the same could apply to issue tracking systems. When using <em>Spock</em> there&#8217;s even a dedicated annotation for tying a feature method or specification class to an issue:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='groovy'><span class='line'><span class="kn">import</span> <span class="nn">spock.lang.*</span>
</span><span class='line'>
</span><span class='line'><span class="nd">@Issue</span><span class="o">(</span><span class="s2">&quot;https://github.com/robfletcher/betamax/issues/34&quot;</span><span class="o">)</span>
</span><span class='line'><span class="kd">class</span> <span class="nc">HttpsProxySpec</span> <span class="kd">extends</span> <span class="n">Specification</span> <span class="o">{</span>
</span></code></pre></td></tr></table></div></figure>


<h2>2: <em>Name</em> tests according to features</h2>

<p>I think part of the reason the habit of associating tests with units of code is hard to break is naming. Test classes have to be called something and that something is limited by Java&#8217;s class naming requirements and conventions. Naming things is often treated as an afterthought, <a href="http://martinfowler.com/bliki/TwoHardThings.html">but it&#8217;s actually hard</a>. When I start working on a card with a description something like <em>&#8220;A user can save articles to a list of &#8216;favourites&#8217;&#8221;</em> what am I going to call the functional test class? I should probably go for <em>UserSavesArticleToFavouritesSpec</em> but if this is the first card played that&#8217;s to do with <em>favourites</em> maybe I&#8217;ll just be lazy and call it <em>FavouritesSpec</em>. Next week someone else plays a card <em>&#8220;Users can remove articles from their list of favourites&#8221;</em> and adds their coverage to my original <em>FavouritesSpec</em> which is now some hybrid beast testing two different bits of behaviour.</p>

<h2>3: Put tests somewhere you can find them later</h2>

<p>Over time something I&#8217;ve noticed is that it becomes difficult to identify where exactly a certain bit of functionality is covered in the functional tests. Team members fixing defects will sometimes try to figure out who implemented something in the first place and ask them where the tests are or even end up trawling through the <em>Git</em> log. This shouldn&#8217;t be necessary.</p>

<p>A corollary to that is that it also becomes difficult to identify redundancy or obsolescence in the functional tests. If a feature of the application is removed or replaced then obviously the tests around it should also be removed. The <em>wrong</em> way to do that is by running everything and deleting whatever fails.</p>

<p>I&#8217;ve also seen test cruft floating around (still &#8216;passing&#8217; somehow) from long-dead features. In some cases so long-dead that we&#8217;ve had to go rooting through the code because we can&#8217;t remember whether the functionality still exists.</p>

<p>Redundancy is a huge problem on some projects. One in particular had a vast suite of <em>Selenese</em> tests that often repeatedly exercised bits of functionality often nothing to do with what the test was concerned with actually testing. For example the CMS used the <em>Grails</em> URL convention of <em>/type/action/id</em> (e.g. <em>/article/edit/1234</em>). Because such URLs are unpredictable tests would do things like invoke a data fixture then use the CMS&#8217;s search tool to find the thing the fixture created and navigate to its edit page.</p>

<h2>4: Keep tests atomic</h2>

<p>There&#8217;s a best practice that states each test should make a single logical assertion and I&#8217;d extend that to say that test classes should test a single feature (including variations and edge cases). If the new test you&#8217;re writing is nothing to do with the other tests in the class or is only related to them because it deals with some of the same parts of the application then it should be broken out into a new class.</p>

<p>Sometimes this comes at the cost of repeated initialization or data setup and developers&#8217; natural DRY instincts resist that. But in the long run well organized tests will pay dividends over pristine DRY-ness especially as the requirements of individual tests have a habit of mutating over time so that what is common now may not stay that way.</p>

<p><em>Selenese</em> tests seem particularly prone to run-on testing where what are in reality multiple tests are combined into one because it is easy for the resulting state of an earlier part of the test to feed into further assertions. For example a test that creates an <em>article</em> then makes sure the user can search for it, then uses the search result to navigate to an edit page where it makes sure the <em>article</em> can be updated and finally deleted. A <a href="http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/" title="James Carr: TDD Anti-Patterns">TDD anti-pattern</a> known as <em>&#8220;The One&#8221;</em>. Spock&#8217;s <em>@Stepwise</em> annotation can be similarly abused.</p>

<h2>5: Isolate data fixtures for each test</h2>

<p>Starting out with simple tests that create some data we&#8217;ll often spot some commonality &amp; move some of the data setup into <em>setup</em> or <em>setupSpec</em> methods (<em>@Before</em> or <em>@BeforeClass</em> in JUnit). When successive cards are played and developers augment that test they&#8217;ll find the original data is insufficient or inappropriate. Before long there&#8217;s a test with some data created in <em>setup</em>, individual tests adding more, some tests ignoring the data from <em>setup</em> completely and worse, some tests actually modifying or even deleting bits of it.</p>

<p>This is not a recipe for a maintainable test. The problems compound themselves. It may not be obvious that one of the tests methods doesn&#8217;t actually need the data provided by the <em>setup</em> method so it gets left there as the test evolves. Eventually it can reach a point where the test has changed so much that virtually <em>none</em> of the individual tests actually need the data provided by the <em>setup</em> method or all of them make significant changes to it but it&#8217;s still sitting there anyway because that fact isn&#8217;t apparent without a very close reading of the code.</p>

<p>I&#8217;m not saying don&#8217;t write tests that share data created in <em>setup</em>. But do it sparingly and don&#8217;t then add tests that don&#8217;t need that data; put them somewhere else.</p>

<p>I do prefer tests that set up their own data rather than relying on a common fixture. I think it makes the test read better: the fixture becomes part of the test&#8217;s preconditions (the <em>given</em> in the BDD <em>given, when, then</em> structure). That&#8217;s not to say that tests can&#8217;t share fixtures. Factory methods, fixture loaders and so on are appropriate ways of doing that.</p>

<p>Grails has a couple of plugins that are very useful here; <em>Fixtures</em> and <em>Build Test Data</em>. I&#8217;m actually pretty bad at using the <em>Fixtures</em> plugin effectively but am convinced it&#8217;s a good idea. <em>Build Test Data</em> is usually among the first plugins I install in any project and it&#8217;s very useful for hiding irrelevant fixture detail from the test code.</p>

<h2>TL;DR version</h2>

<p>I firmly believe that small is good when it comes to functional tests. I want lots of tests each covering some well defined facet of the application&#8217;s behaviour, preferably traceable in some way to the original card. I think if I&#8217;ve understood anything of Behaviour Driven Development it&#8217;s that tests should be organized around product features and not units of code.</p>

<h2><em>Still</em> TL;DR version</h2>

<p>I should probably start using <a href="http://cukes.info/">Cucumber</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Upgrading to Grails 2: Part 1]]></title>
    <link href="http://blog.freeside.co/blog/2011/11/29/grails-2-upgrade-part-1/"/>
    <updated>2011-11-29T00:07:00+00:00</updated>
    <id>http://blog.freeside.co/blog/2011/11/29/grails-2-upgrade-part-1</id>
    <content type="html"><![CDATA[<p>We&#8217;ve recently spent some time ensuring that our application is forwards-compatible with the upcoming Grails 2. Our app is broadly split into the application itself and a large plugin that forms the core of our <a href="http://en.wikipedia.org/wiki/Content_management_system" title="Content management system">CMS</a>. We upgraded the plugin first as it contains the core domain classes but is also a slightly smaller task to tackle. I&#8217;ll write up our findings when we&#8217;ve completed upgrading the application itself in a follow-up to this post.</p>

<p>Although it took a little while I found the upgrade less painful than some previous versions. It feels like Grails is really maturing so there are fewer fundamental breaking changes and more in the way of new features. The bulk of the changes we had to make were to unit tests which are vastly improved in Grails 2. That said, I can see some of the things we ran into stumping people so I thought a write-up would make a useful reference. Some of these items may already be covered by the <a href="http://grails.org/doc/2.0.x/guide/gettingStarted.html#upgradingFromPreviousVersionsOfGrails">upgrading section of the Grails user guide</a> but some, particularly around plugins are probably new.</p>

<!--more-->


<h2>Compilation</h2>

<p>Firstly we needed to do to just get the build working to the point where tests would run.</p>

<h3>Upgrade Spock</h3>

<p>Version <em>0.6-SNAPSHOT</em> of the <a href="http://grails.org/plugin/spock">Spock plugin</a> is required for compatibility with Groovy 1.8.</p>

<p>This also required us to update <code>@Unroll</code> annotations to use <em>Closure</em> parameters. Instead of</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>@Unroll("#a plus #b should equal #x")</span></code></pre></td></tr></table></div></figure>


<p>the annotation needs to be</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>@Unroll({"$a plus $b should equal $x"})</span></code></pre></td></tr></table></div></figure>


<p>Whilst this is a bit of a chore there are some advantages to this format as you can reference properties and call methods on the parameters right in the annotation.</p>

<p>Before the tests would run we got a compilation error:</p>

<pre><code>The return type of java.lang.Object mockDomain(java.lang.Class) in com.sky.cms.AssetSpec is incompatible with void mockDomain(java.lang.Class) in grails.plugin.spock.UnitSpec`
</code></pre>

<p>There&#8217;s some kind of clash between the method signatures of <em>mockDomain</em> in Spock&#8217;s <em>UnitSpec</em> and Grails core. We&#8217;d intended to switch to the new annotation-based unit test support anyway but apparently we needed to do so right away. On the surface this just meant making our specs extend <em>Specification</em> instead of <em>UnitSpec</em> and introducing the new <code>@TestFor</code> annotation. The other changes we had to make to get our tests running successfully are covered below.</p>

<h2>Configuration changes</h2>

<p>Configuration-wise all we had to do was to change <em>DataSource.groovy</em> to reference <em>H2</em> rather than <em>hsqldb</em>. Because we were just dealing with the CMS plugin and its test harness we hadn&#8217;t modified the default file in any way so we just replaced it with the new one from Grails 2 with:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>cp <span class="nv">$GRAILS_HOME</span>/src/grails/grails-app/conf/DataSource.groovy grails-app/conf/
</span></code></pre></td></tr></table></div></figure>


<h2>Unit tests</h2>

<p>The bulk of the time we spent upgrading was spent on unit tests. This is understandable since Grails 2 has made some significant enhancements in unit test support. Most of the changes are pretty straightforward but there are a couple of gotchas here.</p>

<ul>
<li>The <code>mockConfig</code> method was always a bit awkward (as anyone who has tried to assign the path to a <em>File</em> object to a config key on a Windows machine will attest) and has been removed. Unit tests now get a genuine <em>GrailsApplication</em> instance injected by default if using one of the new annotations and you can directly assign values to the <code>config</code> property.</li>
<li>Remove <code>mockDomain</code> calls &amp; add a <code>@TestFor</code> or <code>@Mock</code> annotation to the test class. Use <code>@TestFor(MyDomainClass)</code> for the domain class&#8217; own tests and <code>@Mock(MyDomainClass)</code> when the domain class is a collaborator. <code>@Mock</code> accepts multiple classes if you need it.</li>
<li>We had a number of assertions about domain validation errors that we had to change from <code>domainInstance.errors.&lt;fieldName&gt;</code> to <code>domainInstance.errors.getFieldError('&lt;fieldName&gt;').code</code>. The latter is more long winded but has the advantage of using the same API as when you deal with Spring <em>Errors</em> instances in application code.</li>
<li>Tests for a controller that has an <code>allowedMethods</code> declaration must set the <code>request.method</code> or they get a <em>405: Method Not Allowed</em> response.</li>
<li>Domain class validation is evaluated on mock domain instances. Often this isn&#8217;t actually desirable. Tests cluttered with data setup that is only required to satisfy domain constraints are harder to maintain. To get round this you can use <code>.save(validate: false)</code>.</li>
<li>Domain class event handlers such as <em>beforeInsert</em> are not triggered unless the session is flushed. In the few tests this affected we just had to change <code>.save()</code> to <code>.save(flush: true)</code>.</li>
<li>Assigned ids are wiped from domain object instances when <code>@Mock</code> is used. It seems like even when assigning ids on construction with code like <code>new Pirate(id: 1234, name: "Edward Teach")</code> the <em>id</em> will be <em>null</em> until the <em>save</em> method is called. This wasn&#8217;t a big deal for us &amp; mostly meant getting rid of a few <a href="http://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants">magic numbers</a> from test code.</li>
<li><code>grailsApplication</code> is not wired into domain instances like it is into controllers and tag libs when using <code>@TestFor</code>.</li>
<li>We ran into some issues with tests for property editors where we were setting up mock a <em>request</em> variable. We had a <em>NullPointerException</em> thrown from domain class constructors after doing so. Using the <em>request</em> property provided by <code>@TestMixin(ControllerUnitTestMixin)</code> instead fixed things.</li>
<li>We converted our old tag lib tests to use <code>@TestFor(TagLibClass)</code> and the new <em>applyTemplate</em> method. See the <a href="http://grails.org/doc/2.0.x/guide/testing.html#unitTestingTagLibraries">relevant section of the Grails user guide</a> for more details on this.</li>
<li>Tag libs using <code>@TestFor</code> can actually find and render GSP templates when they call <em>render</em>. This means you might get more realistic output than your test was previously expecting!</li>
<li>We found that when testing tag libs with <code>@TestFor</code> that modifying the metaclass of the <code>taglib</code> field of the test class didn&#8217;t affect tests using <em>applyTemplate</em>. However, we just had to change from <code>taglib.metaClass.blah</code> to <code>MyTagLib.metaClass.blah</code>.</li>
</ul>


<h2>Plugins</h2>

<h3>Joda Time</h3>

<p>We upgraded the <a href="http://gpc.github.com/grails-joda-time/">Joda-Time plugin</a> to version <em>1.3</em>. This also meant we had to add the Hibernate persistence library to the <em>dependencies</em> section of <em>BuildConfig</em> <a href="http://gpc.github.com/grails-joda-time/guide/2.%20Persistence.html">as documented here</a>.</p>

<h3>Resources</h3>

<p>The Resources plugin currently (up to at least version <em>1.1.1</em>) <a href="http://jira.grails.org/browse/GPRESOURCES-109">has a bug</a> that means it does not generate resources properly in anything other than <em>dev</em> mode. There is a workaround; just add the following to <em>BootStrap</em>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>def grailsResourceProcessor
</span><span class='line'>
</span><span class='line'>def <span class="nv">init</span> <span class="o">=</span> <span class="o">{</span>
</span><span class='line'>    grailsResourceProcessor.updateDependencyOrder<span class="o">()</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Geb</h3>

<p>We upgraded <a href="http://gebish.org/">Geb</a> to version <em>0.6.1</em> and the <a href="http://code.google.com/p/selenium/">Selenium</a> drivers to version <em>2.13.0</em>. The only issues we ran into were:</p>

<ul>
<li>An additional dependency is required to handle <code>select</code> elements properly (installation details are handily included in the report for any test that fails due to this).</li>
<li>Setting values on <code>input type="file"</code> elements no longer worked. I&#8217;ve already fixed this issue and it should be in the next <em>Geb</em> release. See <a href="http://jira.codehaus.org/browse/GEB-152">GEB-152</a> for more information.</li>
</ul>


<h2>Other Libraries</h2>

<p>We had one test that used <em><a href="http://code.google.com/p/gmock/">GMock</a></em>. Unfortunately it is not currently compatible with Groovy 1.8. For us this wasn&#8217;t a big deal as we could easily drop <em>GMock</em> but some codebases may be more invested in it.</p>

<h2>Actual Grails bugs</h2>

<p>We only found a couple of problems with Grails itself both of which I&#8217;ve raised on the Grails bug tracker:</p>

<ul>
<li><a href="http://jira.grails.org/browse/GRAILS-8376">GRAILS-8376</a> Constraints on superclass associations are not inherited properly in mock domain instances. This bit us when instances of a child class of a superclass that had an association with <code>nullable: true</code> failed to save. The workaround is to simply duplicate the constraint in the child class (yes, it&#8217;s ugly).</li>
<li><a href="http://jira.grails.org/browse/GRAILS-837y">GRAILS-8377</a> <code>grails test run-app</code> fails with <code>Error loading plugin manager: GebGrailsPlugin</code>. This is kind of an edge case. We were only trying to run the application in test mode to help figure out the problem with resource processing mentioned above.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Welcome to the new Ad-Hockery]]></title>
    <link href="http://blog.freeside.co/blog/2011/11/28/welcome-to-the-new-ad-hockery/"/>
    <updated>2011-11-28T23:59:00+00:00</updated>
    <id>http://blog.freeside.co/blog/2011/11/28/welcome-to-the-new-ad-hockery</id>
    <content type="html"><![CDATA[<p>I&#8217;ve finally taken the plunge and migrated <em>Ad-Hockery</em> from Blogger to the stupendously awesome <a href="http://octopress.org/">Octopress</a> platform as suggested to me by <a href="https://twitter.com/#!/andreasarledal">Andreas Arledal</a>. The old blog will remain available and links to the old posts are maintained in the <a href="http://blog.freeside.co/blog/archives">Archive</a> section here.</p>
]]></content>
  </entry>
  
</feed>

