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

<channel>
	<title>Ted Naleid &#187; unit testing</title>
	<atom:link href="http://naleid.com/blog/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://naleid.com/blog</link>
	<description>Groovy, Grails and OS X tips and tricks</description>
	<lastBuildDate>Wed, 16 Jun 2010 17:38:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Grails Testing Alias to Rerun Failed Tests</title>
		<link>http://naleid.com/blog/2009/11/03/grails-testing-alias-to-rerun-failed-tests/</link>
		<comments>http://naleid.com/blog/2009/11/03/grails-testing-alias-to-rerun-failed-tests/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 03:29:58 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[command line]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[shortcut]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[zshrc]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=99</guid>
		<description><![CDATA[A while ago I blogged about my grails testing aliases and how much time they save me.
I&#8217;ve made some enhancements to them in the interim that have made them even easier to use.  
The most important alias is gtaf, which is short for &#8220;grails test-app&#8221; for failed tests.
It will search through your test output [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I <a href="http://naleid.com/blog/2009/06/14/grails-testing-command-line-aliases/">blogged about my grails testing aliases</a> and how much time they save me.</p>
<p>I&#8217;ve made some enhancements to them in the interim that have made them even easier to use.  </p>
<p>The most important alias is <code>gtaf</code>, which is short for &#8220;grails test-app&#8221; for failed tests.</p>
<p>It will search through your test output directory and look for any tests that failed.  If it finds any, it will rerun only those tests.  Otherwise, it will rerun all tests.  That makes it easy to just use <code>gtaf</code> all the time.  If any tests fail, it will open them up using Console.app.  </p>
<p>If you&#8217;re not on OSX, or would like to use something else to view the failed test logs, just modify the <code>testlog</code> alias to do something different.<br />
<span id="more-99"></span><br />
There are alternative versions of it to only run failed integration tests (<code>gtaif</code> &#8211; Grails Test App Integration Failed), failed unit tests (<code>gtauf</code> &#8211; Grails Test App Unit Failed) or attach a debugger to the tests as they run (<code>gtadf</code> &#8211; Grails Test App Debug Failed).</p>
<p>These aliases, plus most of the rest of my zsh setup, is <a href="http://bitbucket.org/tednaleid/shared-zshrc/src/" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/shared-zshrc/src/?referer=');">available on bitbucket</a>.  If you haven&#8217;t used zsh before and are still using bash, I suggest <a href="http://naleid.com/blog/2009/05/13/shared-zshrc-file/">switching over for the numerous benefits that it gives you</a>.</p>
<p>Here&#8217;s the section of zshrc_general that has the grails testing aliases, just add this to your .zshrc/.bashrc and make sure to uncomment the appropriate GRAILS_TEST_LOG_DIRECTORY export if you&#8217;re not running grails 1.2 yet:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># grails &gt; 1.2</span>
<span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #007800;">GRAILS_TEST_LOG_DIRECTORY</span>=target<span style="color: #000000; font-weight: bold;">/</span>test-reports
&nbsp;
<span style="color: #666666; font-style: italic;"># grails &lt; 1.2</span>
<span style="color: #666666; font-style: italic;"># export GRAILS_TEST_LOG_DIRECTORY=test/reports</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># after grails-test if there were ERROR messages, you can open those logs with the Console.app using this</span>
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">testlog</span>=<span style="color: #ff0000;">'for F in `grep -lE &quot;FAILED|Caused\ an\ ERROR&quot; $GRAILS_TEST_LOG_DIRECTORY/plain/*.txt`; do echo &quot;&gt;&gt;&gt; opening&quot; $F; open -a Console $F; done;'</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># grails-debug-suspend doesn't exist by default, it's a copy of grails-debug with the suspend flag changed to &quot;y&quot; so that</span>
<span style="color: #666666; font-style: italic;"># we can attach a remote debugger before it proceeds past startup</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># aliases where you can optionally pass in a set of tests to run (or no argument to run all tests in that group)</span>
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gta</span>=grailsTestApp
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtad</span>=grailsTestAppDebug
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtau</span>=grailsTestAppUnit
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaud</span>=grailsTestAppUnitDebug
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtai</span>=grailsTestAppIntegration
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaid</span>=grailsTestAppIntegrationDebug
&nbsp;
<span style="color: #666666; font-style: italic;"># aliases that will rerun any failed tests (or all tests if there aren't any failed tests)</span>
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaf</span>=grailsTestAppFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtadf</span>=grailsTestAppDebugFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtauf</span>=grailsTestAppUnitFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaudf</span>=grailsTestAppUnitDebugFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaif</span>=grailsTestAppIntegrationFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaidf</span>=grailsTestAppIntegrationDebugFailed
&nbsp;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestApp<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #ff0000;">&quot;&quot;</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails <span style="color: #ff0000;">&quot;&quot;</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #ff0000;">&quot;&quot;</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppDebugFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails-debug-suspend <span style="color: #ff0000;">&quot;&quot;</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnit<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #660033;">-unit</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnitFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails <span style="color: #660033;">-unit</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnitDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #660033;">-unit</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnitDebugFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails-debug-suspend <span style="color: #660033;">-unit</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegration<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #660033;">-integration</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegrationFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails <span style="color: #660033;">-integration</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegrationDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #660033;">-integration</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegrationDebugFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails-debug-suspend <span style="color: #660033;">-integration</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsFailedTests<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
	<span style="color: #007800;">FAILED_TESTS</span>=<span style="color: #ff0000;">''</span>
	<span style="color: #000000; font-weight: bold;">for</span> F <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #660033;">-lE</span> <span style="color: #ff0000;">&quot;FAILED|Caused\ an\ ERROR&quot;</span> <span style="color: #007800;">$GRAILS_TEST_LOG_DIRECTORY</span><span style="color: #000000; font-weight: bold;">/</span>plain<span style="color: #000000; font-weight: bold;">/*</span>.txt<span style="color: #000000; font-weight: bold;">`</span>; <span style="color: #000000; font-weight: bold;">do</span>
		<span style="color: #007800;">FAILED_TESTS</span>=<span style="color: #ff0000;">&quot;<span style="color: #007800;">$FAILED_TESTS</span> <span style="color: #780078;">`echo $F | sed -E 's/.*TEST-(.*)Tests.txt/\1/g'`</span>&quot;</span>
	<span style="color: #000000; font-weight: bold;">done</span>;
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;failed tests: <span style="color: #007800;">$FAILED_TESTS</span>&quot;</span>
	grailsTest $<span style="color: #000000;">1</span> $<span style="color: #000000;">2</span> <span style="color: #007800;">$FAILED_TESTS</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTest<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Running: $1 test-app $2 $3 || testlog &quot;</span>
    <span style="color: #000000; font-weight: bold;">time</span> $<span style="color: #000000;">1</span> test-app $<span style="color: #000000;">2</span> $<span style="color: #000000;">3</span> <span style="color: #000000; font-weight: bold;">||</span> testlog
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

<p>I believe that they&#8217;ll also work fine as-is in bash, though I haven&#8217;t tested them.</p>
<p><script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/11/03/grails-testing-alias-to-rerun-failed-tests/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Grails build-test-data presentation</title>
		<link>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/</link>
		<comments>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 03:28:56 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=59</guid>
		<description><![CDATA[I gave a presentation tonight on the build-test-data grails plugin at the Groovy Users of Minnesota (GUM) meeting that was well received.
Lots of good questions from the people in attendance.  Thanks to everyone for showing up.
Here&#8217;s a version of it on slideshow:
Grails build-test-data Plugin
View more documents from tednaleid.

I also released a new bugfix version [...]]]></description>
			<content:encoded><![CDATA[<p>I gave a presentation tonight on the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">build-test-data</a> grails plugin at the <a href="http://groovy.mn" onclick="pageTracker._trackPageview('/outgoing/groovy.mn?referer=');">Groovy Users of Minnesota (GUM)</a> meeting that was well received.</p>
<p>Lots of good questions from the people in attendance.  Thanks to everyone for showing up.</p>
<p>Here&#8217;s a version of it on slideshow:<span id="more-59"></span></p>
<div style="width:650px;text-align:left" id="__ss_1723277"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/tednaleid/grails-buildtestdata-plugin-1723277" title="Grails build-test-data Plugin" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/tednaleid/grails-buildtestdata-plugin-1723277?referer=');">Grails build-test-data Plugin</a><object style="margin:0px" width="650" height="547"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=build-test-datapresentation-090714222053-phpapp01&#038;stripped_title=grails-buildtestdata-plugin-1723277" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=build-test-datapresentation-090714222053-phpapp01&#038;stripped_title=grails-buildtestdata-plugin-1723277" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="650" height="547"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/?referer=');">documents</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/tednaleid" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/tednaleid?referer=');">tednaleid</a>.</div>
</div>
<p>I also released a new bugfix version of build-test-data earlier today (0.2.2).  Mostly fixed bugs, but there&#8217;s also a new config setting that lets you disable the plugin in specified environments (suggested by Scott Vlaminck @ <a href="http://refactr.com"/>refactr</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Groovy closures make unit testing with &#8220;soft asserts&#8221; simple</title>
		<link>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/</link>
		<comments>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 04:25:45 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[closures]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=58</guid>
		<description><![CDATA[A recent blog post, Cedric Beust asks about how to cleanly implement &#8220;soft asserts&#8221;.  Soft asserts are test assertions that don&#8217;t &#8220;fail fast&#8221;.  Instead, all of the assertion failures in the test method are collected and reported at the end of the test.
So far, the proposals in the comments look fairly clunky to [...]]]></description>
			<content:encoded><![CDATA[<p>A recent blog post, <a href="http://beust.com/weblog/archives/000514.html" onclick="pageTracker._trackPageview('/outgoing/beust.com/weblog/archives/000514.html?referer=');">Cedric Beust asks about how to cleanly implement &#8220;soft asserts&#8221;</a>.  Soft asserts are test assertions that don&#8217;t &#8220;fail fast&#8221;.  Instead, all of the assertion failures in the test method are collected and reported at the end of the test.</p>
<p>So far, the proposals in the comments look fairly clunky to me and include defining whole sets of new methods like &#8220;assertEqualsButContinue(&#8220;foo&#8221;, &#8220;foo&#8221;)&#8221;, chaning assertions together jQuery-style, or using lists to hold all of our assertions.</p>
<p>Wouldn&#8217;t it be a lot nicer if we could continue to use the same methods that we&#8217;re already using?</p>
<p>In groovy, enabling soft assertions is easy with a little closure magic.<span id="more-58"></span></p>
<p>Closures have a property called the &#8220;resolveStrategy&#8221; that determines where the code inside the closure should look to resolve method names.  The default resolve strategy is OWNER_FIRST.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">Closure closure <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;foo&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #000000; font-weight: bold;">assert</span> closure.<span style="color: #006600;">getResolveStrategy</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">==</span> Closure.<span style="color: #006600;">OWNER_FIRST</span></pre></div></div>

<p>OWNER_FIRST means that if something isn&#8217;t defined inside the closure (local scope), it should check the owner of the closure to see if it can resolve it.  The owner of the closure is the declaring class or another closure that contains our closure.</p>
<p>Closures also have a property called the &#8220;delegate&#8221;.  By default, the delegate is equal to the owner, but we have the ability to change the delegate to something else.  We can also change the resolveStrategy for the closure so when something isn&#8217;t defined, the delegate is the first place that is checked.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Original <span style="color: #669966;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">def</span> closure <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> value<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#125;</span>   
&nbsp;
   <span style="color: #000000; font-weight: bold;">def</span> value <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> SomethingElse <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> value <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;value from delegate&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> obj <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Original<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// the owner is the enclosing class, and its the same as the delegate by default</span>
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">owner</span>.<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #669966;">==</span> Original
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">owner</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">delegate</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// but we can change the closure's delegate to something else if we want</span>
obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">delegate</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SomethingElse<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// by default, the closure looks at the owner before the delegate, value is unchanged</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> 
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">getResolveStrategy</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">==</span> Closure.<span style="color: #006600;">OWNER_FIRST</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// changing the closure's resolve strategy switches who gets to handle value()</span>
obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">resolveStrategy</span> <span style="color: #669966;">=</span> Closure.<span style="color: #006600;">DELEGATE_FIRST</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from delegate&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Groovy also has a <a href="http://groovy.codehaus.org/Using+invokeMethod+and+getProperty" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Using+invokeMethod+and+getProperty?referer=');">special metaClass method called invokeMethod</a> that allows you to manipulate any method calls that are invoked on that metaClass.</p>
<p>Using these two things in conjunction, we can write a small class that lets us collect JUnit assertion errors thrown by any method starting with &#8220;assert&#8221;.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> SoftAsserts <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> oldDelegate
    <span style="color: #000000; font-weight: bold;">def</span> failedAssertions <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">static</span> softAsserts<span style="color: #669966;">&#40;</span>closure<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">new</span> SoftAsserts<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">bundleAsserts</span><span style="color: #669966;">&#40;</span>closure<span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> bundleAsserts <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> closure <span style="color: #669966;">-&gt;</span>
        closure.<span style="color: #006600;">resolveStrategy</span> <span style="color: #669966;">=</span> Closure.<span style="color: #006600;">DELEGATE_ONLY</span>
        oldDelegate <span style="color: #669966;">=</span> closure.<span style="color: #006600;">delegate</span>
        closure.<span style="color: #006600;">delegate</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">this</span>
        closure<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>   
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>failedAssertions<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Exception</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;${failedAssertions.size()} failed assertions found:<span style="color: #000099; font-weight: bold;">\n</span>${failedAssertions.message.join('<span style="color: #000099; font-weight: bold;">\n</span>')}&quot;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> <span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, args<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>name.<span style="color: #006600;">startsWith</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;assert&quot;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #669966;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> oldDelegate.<span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span>name, args<span style="color: #669966;">&#41;</span>
            <span style="color: #669966;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #669966;">&#40;</span>junit.<span style="color: #006600;">framework</span>.<span style="color: #006600;">AssertionFailedError</span> e<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
                failedAssertions <span style="color: #669966;">&lt;&lt;</span> e
            <span style="color: #669966;">&#125;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> oldDelegate.<span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span>name, args<span style="color: #669966;">&#41;</span>         
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>This test class does a static import of the SoftAsserts.softAsserts closure so it can use it in a natural way.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #996600;">grails.test.*</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #996600;">static</span> SoftAsserts.<span style="color: #006600;">softAsserts</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> BookTests <span style="color: #000000; font-weight: bold;">extends</span> GroovyTestCase <span style="color: #669966;">&#123;</span>
    <span style="color: #993333;">void</span> testBookTrueAssertsPasses<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> book <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>title: <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span><span style="color: #669966;">&#93;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// all 4 assertions pass and we are able to refer to local variables </span>
        <span style="color: #808080; font-style: italic;">// like book and local methods like trueMethod() </span>
        softAsserts <span style="color: #669966;">&#123;</span> 
            assertTrue <span style="color: #000000; font-weight: bold;">true</span>
            assertTrue trueMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
            assertNotNull book
            assertEquals <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span>, book.<span style="color: #006600;">title</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #993333;">void</span> testBookFalseAssertsCollectsFailures<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> book <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>title: <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span><span style="color: #669966;">&#93;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// all 4 assertions throw errors, but all are collected before </span>
        <span style="color: #808080; font-style: italic;">// an exception is actually thrown</span>
        softAsserts <span style="color: #669966;">&#123;</span> 
            assertTrue <span style="color: #aa0000;">&quot;False is not true&quot;</span>, <span style="color: #000000; font-weight: bold;">false</span>
            assertTrue <span style="color: #aa0000;">&quot;falseMethod() is not true&quot;</span>, falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
            assertNull <span style="color: #aa0000;">&quot;Book is not null&quot;</span>, book
            assertEquals <span style="color: #aa0000;">&quot;House of Leaves&quot;</span>, book.<span style="color: #006600;">title</span>
        <span style="color: #669966;">&#125;</span>   
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> trueMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">true</span> <span style="color: #669966;">&#125;</span>   
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">false</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>The first test shows how a passing test can successfully refer to other variables and methods defined inside the test class.  The second test fails, but it doesn&#8217;t fail till all 4 of the assertions are tried and collected.  It then throws an error with the assertion failure count and the individual error messages:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">Testcase: testBookFalseAssertsCollectsFailures took <span style="color: #cc66cc;">0.371</span> sec
	Caused an ERROR
<span style="color: #cc66cc;">4</span> failed assertions found:
<span style="color: #000000; font-weight: bold;">False</span> is not <span style="color: #000000; font-weight: bold;">true</span>
falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> is not <span style="color: #000000; font-weight: bold;">true</span>
<span style="color: #aaaadd; font-weight: bold;">Book</span> is not <span style="color: #000000; font-weight: bold;">null</span>
expected:<span style="color: #669966;">&lt;</span><span style="color: #669966;">&#91;</span>House of Leaves<span style="color: #669966;">&#93;</span><span style="color: #669966;">&gt;</span> but was:<span style="color: #669966;">&lt;</span><span style="color: #669966;">&#91;</span>Infinite Jest<span style="color: #669966;">&#93;</span><span style="color: #669966;">&gt;</span></pre></div></div>

<p>It might be useful to also print out the individual stack traces for each assertion error, but this is left as an exercise for the reader.</p>
<p>In most situations, I like the fail fast behavior and limiting tests to exercising one feature at a time, but there have been a few test cases where something like this would&#8217;ve been nice.<br />
<script type="text/javascript">var dzone_url = 'http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Grails plugin build-test-data 0.2.1 released</title>
		<link>http://naleid.com/blog/2009/06/15/grails-plugin-build-test-data-021-released/</link>
		<comments>http://naleid.com/blog/2009/06/15/grails-plugin-build-test-data-021-released/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 05:37:20 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[command line]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[integration testing]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=56</guid>
		<description><![CDATA[I&#8217;ve just released version 0.2.1 of the build-test-data grails plugin.
The build-test-data plugin makes creating integration test data easy.  It decorates your domain objects with a &#8220;build&#8221; method that will create new domain instances and will automatically populate required fields with data and save it to the database.  This enables you to create more [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just released version 0.2.1 of the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">build-test-data grails plugin</a>.</p>
<p>The build-test-data plugin makes creating integration test data easy.  It decorates your domain objects with a &#8220;build&#8221; method that will create new domain instances and will automatically populate required fields with data and save it to the database.  This enables you to create more maintainable tests where the data you create is targeted specifically at the situations you&#8217;re trying to test, without having to go through all of the ceremony of creating the rest of the object graph that you don&#8217;t care about.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// creates a new Book instance with all required fields </span>
<span style="color: #808080; font-style: italic;">// (like the Author that the book belongsTo) populated</span>
<span style="color: #000000; font-weight: bold;">def</span> b <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">Book</span>.<span style="color: #006600;">build</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>To learn more about the basics of the build-test-data plugin, see <a href="http://naleid.com/blog/2009/04/14/grails-build-test-data-01-plugin-released/">this blog post</a> and check out the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/BasicUsage" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/BasicUsage?referer=');">Basic Usage</a> and <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/SampleCode" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/SampleCode?referer=');">Sample Code</a> wiki pages.<br />
<span id="more-56"></span><br />
To install, just run the install-plugin grails command (this will also upgrade an existing plugin):</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">grails install-plugin build-test-data</pre></div></div>

<p>The 0.2 version of the plugin includes a number of enhancements and <a href="http://bitbucket.org/tednaleid/grails-test-data/issues/" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/issues/?referer=');">bugfixes</a>.  Major highlights include:</p>
<ul>
<li>
JodaTime support (along with any other persistable class with a zero argument constructor)
</li>
<li>
much easier and more powerful config files (see the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/TestDataConfig" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/TestDataConfig?referer=');">TestDataConfig</a> wiki page for details and examples)
</li>
</ul>
<p>Additionally, the code has been cleaned up and refactored to be easier to understand.</p>
<p>See the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/ReleaseNotes" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/ReleaseNotes?referer=');">Release Notes</a> wiki page for full details. </p>
<p>I&#8217;d be interested to hear any further feedback on this plugin and other features that people might find useful.  I&#8217;ve successfully been using it on my current project and it&#8217;s been a big help in keeping my tests clean and free from superfluous object construction code, as well as flexible in that it automatically adapts to a changing domain model.</p>
<p><script type="text/javascript">var dzone_url = 'http://naleid.com/blog/2009/06/15/grails-plugin-build-test-data-021-released/';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/06/15/grails-plugin-build-test-data-021-released/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Grails Testing Command Line Aliases</title>
		<link>http://naleid.com/blog/2009/06/14/grails-testing-command-line-aliases/</link>
		<comments>http://naleid.com/blog/2009/06/14/grails-testing-command-line-aliases/#comments</comments>
		<pubDate>Sun, 14 Jun 2009 05:30:57 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[command line]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=55</guid>
		<description><![CDATA[I&#8217;ve recently thrown together a few different command line aliases that have been very helpful in my grails development and I thought others might benefit from them.
The aliases are primarily just the first letter of the words in the command, which makes them easy to remember (and saves on typing).  Some examples:

gta   [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently thrown together a few different command line aliases that have been very helpful in my grails development and I thought others might benefit from them.</p>
<p>The aliases are primarily just the first letter of the words in the command, which makes them easy to remember (and saves on typing).  Some examples:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">gta                   <span style="color: #666666; font-style: italic;"># grails test-app</span>
gtai                  <span style="color: #666666; font-style: italic;"># grails test-app -integration</span>
gtaud AuthorService   <span style="color: #666666; font-style: italic;"># grails-debug-suspend test-app -unit AuthorService</span></pre></div></div>

<p><span id="more-55"></span>My testing aliases are probably my most often used grails aliases.  They&#8217;re all &#8220;gta&#8221; (for grails test-app) followed by an optional &#8220;u&#8221; or &#8220;i&#8221; (to run only unit or integration).</p>
<p>There&#8217;s also an alternate for each of those commands with a &#8220;d&#8221; on the end for &#8220;debug&#8221;.  I call a script named &#8220;grails-debug-suspend&#8221; which is simply a copy of the normal &#8220;grails-debug&#8221; command, but with the &#8220;suspend&#8221; flag set to &#8220;y&#8221;.  This causes the application to stop right away till you attach a remote debugger.  This is very useful for quick tests as its often the case that the code gets past where you have breakpoints set before you launch the debugger.</p>
<p>These commands all also let you pass in the name of a specific test class so that only that test runs.</p>
<p>The overall format for all of the aliases is:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">gta<span style="color: #7a0874; font-weight: bold;">&#91;</span>i<span style="color: #000000; font-weight: bold;">|</span>u<span style="color: #7a0874; font-weight: bold;">&#93;</span><span style="color: #7a0874; font-weight: bold;">&#91;</span>d<span style="color: #7a0874; font-weight: bold;">&#93;</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>TestClassName<span style="color: #7a0874; font-weight: bold;">&#93;</span></pre></div></div>

<p>This example suspends until a debugger is attached and then runs the AuthorServiceTests.groovy unit test class:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">gtaud AuthorService</pre></div></div>

<p>These aliases are all set up to run the &#8220;testlog&#8221; alias if a failing exit code is returned from the test run.  This searches through all of the testlog results for any failures and automatically opens up each failing testlog in the OSX Console.app (if you&#8217;re on another platform, just substitute a different editor).  I wrote <a href="http://naleid.com/blog/2008/03/13/using-the-osx-consoleapp-to-aid-grails-test-driven-development/">a more detailed post a while ago about how nice Console.app is for looking at grails test logs</a>.</p>
<p>Lastly, each command is also run with the unix &#8220;time&#8221; command, which I find useful to help me see how long my tests are taking and get a feel over time for the overall performance of the system under test.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># grails-debug-suspend doesn't exist by default, it's a copy of grails-debug with the suspend flag changed to &quot;y&quot; so that</span>
<span style="color: #666666; font-style: italic;"># we can attach a remote debugger before it proceeds past startup</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gta</span>=grailsTestApp
<span style="color: #000000; font-weight: bold;">function</span> grailsTestApp<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #ff0000;">&quot;&quot;</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtad</span>=grailsTestAppDebug
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #ff0000;">&quot;&quot;</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtau</span>=grailsTestAppUnit
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnit<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #660033;">-unit</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaud</span>=grailsTestAppUnitDebug
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnitDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #660033;">-unit</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtai</span>=grailsTestAppIntegration
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegration<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #660033;">-integration</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaid</span>=grailsTestAppIntegrationDebug
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegrationDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #660033;">-integration</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTest<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Running: $1 test-app $2 $3 || testlog &quot;</span>
    <span style="color: #000000; font-weight: bold;">time</span> $<span style="color: #000000;">1</span> test-app $<span style="color: #000000;">2</span> $<span style="color: #000000;">3</span> <span style="color: #000000; font-weight: bold;">||</span> testlog
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># after grails test if there were ERROR messages, you can open those logs with the Console.app using this</span>
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">testlog</span>=<span style="color: #ff0000;">'for F in `grep -lE &quot;FAILED|Caused\ an\ ERROR&quot; test/reports/plain/*.txt`; do echo &quot;&gt;&gt;&gt; opening&quot; $F; open -a Console $F; done;'</span></pre></div></div>

<p>You can place these aliases in your .bashrc/.bash_profile in your home directory (you can also use them with <a href="http://www.cygwin.com/" onclick="pageTracker._trackPageview('/outgoing/www.cygwin.com/?referer=');">cygwin</a> on windows.</p>
<p>Alternatively, if you&#8217;re using zsh (or interested in switching from bash), I&#8217;ve got all of my zsh setup <a href="http://naleid.com/blog/2009/05/13/shared-zshrc-file/">shared in a source control repo</a> in a format that&#8217;s easy to use and extend for yourself.</p>
<p>This is the modified grails-debug command called grails-debug-suspend, just put it somewhere in your PATH and make it executable (chmod +x grails-debug-suspend):</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #007800;">DIRNAME</span>=<span style="color: #007800;">$GRAILS_HOME</span><span style="color: #000000; font-weight: bold;">/</span>bin
. <span style="color: #ff0000;">&quot;<span style="color: #007800;">$DIRNAME</span>/startGrails&quot;</span>
&nbsp;
<span style="color: #007800;">JAVA_OPTS</span>=<span style="color: #ff0000;">&quot;<span style="color: #007800;">$JAVA_OPTS</span> -Xdebug -Xnoagent -Dgrails.full.stacktrace=true -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005&quot;</span>
startGrails org.codehaus.groovy.grails.cli.GrailsScriptRunner <span style="color: #ff0000;">&quot;$@&quot;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/06/14/grails-testing-command-line-aliases/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Grails build-test-data Plugin Released!</title>
		<link>http://naleid.com/blog/2009/04/14/grails-build-test-data-01-plugin-released/</link>
		<comments>http://naleid.com/blog/2009/04/14/grails-build-test-data-01-plugin-released/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 02:34:58 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[shortcut]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=51</guid>
		<description><![CDATA[Creating maintainable test data is hard. 
Often an entire object graph needs to be created to support the instantiation of a single domain object. This leads to either the cutting and pasting of that creation code, or relying on a canned set of objects that we&#8217;ve grown over time and maintained as the domain objects [...]]]></description>
			<content:encoded><![CDATA[<p>Creating maintainable test data is hard. </p>
<p>Often an entire object graph needs to be created to support the instantiation of a single domain object. This leads to either the cutting and pasting of that creation code, or relying on a canned set of objects that we&#8217;ve grown over time and maintained as the domain objects change. After a while, adding just one more Widget to that set of canned data ends up breaking tests just about every time.</p>
<p>There has to be a better solution, right?<span id="more-51"></span></p>
<p>Yep! Due to the &#8220;Power and the Glory of Grails&#8221;&trade;, we have a lot of metadata at our fingertips about those domain objects. We know what <a href="http://grails.org/doc/1.1/guide/single.html#7.1%20Declaring%20Constraints" onclick="pageTracker._trackPageview('/outgoing/grails.org/doc/1.1/guide/single.html_7.1_20Declaring_20Constraints?referer=');">validation constraints</a> we&#8217;ve placed on our objects, and which objects depend on other objects to live.</p>
<p>Using this additional information, Joe Hoover and I have created a <a href="http://grails.org/plugin/build-test-data" onclick="pageTracker._trackPageview('/outgoing/grails.org/plugin/build-test-data?referer=');">grails plugin called &#8220;build-test-data&#8221;</a>.  With it, you can create test data and omit the fields that you don&#8217;t care about for your test.  The plugin takes care of populating the values required by constraints and persists your domain objects to the database.</p>
<p>This plugin is focused on creating test data for integration testing. If you&#8217;re doing unit testing, there are a number of mocking solutions out there (including a few ways to do it built right into groovy). Unit testing only goes so far though, and if you want to ensure that your code works when it&#8217;s hooked up to a real database, with real transactions, saving, triggers, etc, you&#8217;re only going to get that from an integration test.</p>
<p>Installation of the plugin is easy.  Just run this grails task in the root of your project:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">grails install-plugin build-test-data</pre></div></div>

<p>When the plugin is installed, most domain object should be able to be instantiated and persisted out of the box.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// automatically creates/saves a Book with all required fields populated</span>
<span style="color: #000000; font-weight: bold;">def</span> book <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">Book</span>.<span style="color: #006600;">build</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Once installed, all you have to do is call the new <code>build()</code> method on your domain class and you&#8217;ll be given a valid instance that has been persisted to the database.</p>
<p>It will populate the required fields as defined by the constraints and it has the ability to deal with <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Features" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Features?referer=');">almost all of them</a>.</p>
<p>A couple of them, such as custom validations and regular expressions, are very difficult to work with so if a sample value that we try doesn&#8217;t get past validation, we&#8217;ll throw an error.</p>
<h3>Build Test Data Example</h3>
<p>Here&#8217;s a quick example.  Say you have the following domain objects:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// grails-app/domain/Author.groovy</span>
<span style="color: #000000; font-weight: bold;">class</span> Author <span style="color: #669966;">&#123;</span>
    <span style="color: #aaaadd; font-weight: bold;">String</span> firstName
    <span style="color: #aaaadd; font-weight: bold;">String</span> lastName
    <span style="color: #000000; font-weight: bold;">static</span> hasMany <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>books: <span style="color: #aaaadd; font-weight: bold;">Book</span><span style="color: #669966;">&#93;</span>    
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// grails-app/domain/Book.groovy</span>
<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #aaaadd; font-weight: bold;">Book</span> <span style="color: #669966;">&#123;</span>
    <span style="color: #aaaadd; font-weight: bold;">String</span> title
    <span style="color: #aaaadd; font-weight: bold;">Date</span> published
    <span style="color: #aaaadd; font-weight: bold;">BigDecimal</span> price
    <span style="color: #000000; font-weight: bold;">static</span> belongsTo <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>author: Author<span style="color: #669966;">&#93;</span>    
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>Remember that grails properties are required unless nullable is explicitly set to false, so all of those properties are required.</p>
<p>If you&#8217;re testing a BookPurchasingService and the method you&#8217;re calling needs a Book, normally you&#8217;d need to also create an Author to go with it.  Here&#8217;s how you might normally create your test data without the build-test-data plugin:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #993333;">void</span> testPurchaseBookService<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">def</span> author <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Author<span style="color: #669966;">&#40;</span>firstName: <span style="color: #aa0000;">&quot;first&quot;</span>, lastName: <span style="color: #aa0000;">&quot;last&quot;</span><span style="color: #669966;">&#41;</span>
	author.<span style="color: #006600;">save</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
	<span style="color: #aaaadd; font-weight: bold;">Book</span> tenDollarBook <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Book</span><span style="color: #669966;">&#40;</span>author: author, title: <span style="color: #aa0000;">&quot;title&quot;</span>, published: <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Date</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>, price: <span style="color: #cc66cc;">10.00</span> <span style="color: #000000; font-weight: bold;">as</span> <span style="color: #aaaadd; font-weight: bold;">BigDecimal</span><span style="color: #669966;">&#41;</span>
	tenDollarBook.<span style="color: #006600;">save</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">def</span> result <span style="color: #669966;">=</span> service.<span style="color: #006600;">purchaseBook</span><span style="color: #669966;">&#40;</span>tenDollarBook<span style="color: #669966;">&#41;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//... assertions about expected result of service call</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>You need to create an Author just to create the Book, even though your service only cares about the Book.  If the Author class ever adds an additional required field, you not only need to update all of your Author test classes, but all of your Book test classes as well.</p>
<p>Additionally, there&#8217;s all kinds of &#8220;noise&#8221; in your test class that makes it more difficult to understand exactly what it is you&#8217;re trying to test.</p>
<p>If you&#8217;ve got the build-test-data plugin installed, you don&#8217;t need to worry about any of that.  Creating sample data is easy and you can specify only the parameters that you actually need specific values in to exercise your test.  The plugin will fill in the rest and persist it to the database automatically.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #993333;">void</span> testPurchaseBookService<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">def</span> result <span style="color: #669966;">=</span> service.<span style="color: #006600;">purchaseBook</span><span style="color: #669966;">&#40;</span> <span style="color: #aaaadd; font-weight: bold;">Book</span>.<span style="color: #006600;">build</span><span style="color: #669966;">&#40;</span>price: <span style="color: #cc66cc;">10.00</span> <span style="color: #000000; font-weight: bold;">as</span> <span style="color: #aaaadd; font-weight: bold;">BigDecimal</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#41;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//... assertions about expected result of service call</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>Behind the scenes, build-test-data populates the Book.title and Book.purchased fields, it also creates a new Author with a firstName and lastName and saves all of that to the database.</p>
<p>This test is much cleaner as you only see the things that actually matter to the test and none of the administrative flotsam and jetsam needed to set things up.</p>
<p>In the repository on the bitbucket website, there is <a href="http://bitbucket.org/tednaleid/grails-test-data/src/tip/bookStore/grails-app/domain/bookstore/" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/src/tip/bookStore/grails-app/domain/bookstore/?referer=');">a test &#8220;bookstore&#8221; grails application</a> that has a fairly complex domain model that exercises the build-test-data build method and it&#8217;s ability to serialize an object graph.</p>
<p>Check out the full set of documentation on the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">bitbucket build-test-data wiki</a> and let Joe and I know what you think of it.</p>
<p><script type="text/javascript">var dzone_url = 'http://naleid.com/blog/2009/04/14/grails-build-test-data-01-plugin-released/';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/04/14/grails-build-test-data-01-plugin-released/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>Using Groovy Regular Expressions to Parse Code From a Markdown File</title>
		<link>http://naleid.com/blog/2009/01/01/using-groovy-regular-expressions-to-parse-code-from-a-markdown-file/</link>
		<comments>http://naleid.com/blog/2009/01/01/using-groovy-regular-expressions-to-parse-code-from-a-markdown-file/#comments</comments>
		<pubDate>Thu, 01 Jan 2009 16:55:37 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[groovy]]></category>
		<category><![CDATA[shortcut]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[groovymag]]></category>
		<category><![CDATA[jig]]></category>
		<category><![CDATA[markdown]]></category>
		<category><![CDATA[regexp]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[shim]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=41</guid>
		<description><![CDATA[The January 2009 issue of GroovyMag was released today.  In it, I&#8217;ve written an article that shows how easy regular expressions are to use in groovy.  It starts with some regular expression basics, shows some common idiomatic groovy usage patterns and wraps up with some of the cool new features that groovy 1.6 [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.groovymag.com/main.issues.description/id=5/" onclick="pageTracker._trackPageview('/outgoing/www.groovymag.com/main.issues.description/id=5/?referer=');">January 2009 issue of GroovyMag</a> was released today.  In it, I&#8217;ve written an article that shows how easy regular expressions are to use in groovy.  It starts with some regular expression basics, shows some common idiomatic groovy usage patterns and wraps up with some of the cool new features that groovy 1.6 is adding to regexp handling.</p>
<p>There are over 30 code samples in then article and I wanted to make sure while writing and editing that all of the code samples ran exactly as they appeared in the article text.  Also, when you download an issue of GroovyMag, you get a zip file that has a PDF and a set of code &#8220;listing&#8221; files for each article.  Each listing file contains a snippet of groovy code that appeared in the issue.</p>
<p><a href='http://naleid.com/blog/wp-content/uploads/2009/01/listings.png'><img src="http://naleid.com/blog/wp-content/uploads/2009/01/listings.png" alt="Directory screenshot showing listing files" title="listings" class="alignnone size-full wp-image-43" /></a></p>
<p>I decided to write a couple of simple groovy scripts to keep things <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Don_27t_repeat_yourself?referer=');">DRY</a>, and to ensure that my edits didn&#8217;t break anything.  The first script extracts code listings out of my draft article and saved them to individually numbered listing files.  The second script executes each of the listing files and reported success or failure for each.  Sort of a poor man&#8217;s JUnit for writing articles.</p>
<p><span id="more-41"></span></p>
<p>Both of these scripts leverage regular expressions and the techniques that are outlined in GroovyMag.</p>
<p>I wrote the article using the <a href="http://daringfireball.net/projects/markdown/syntax" onclick="pageTracker._trackPageview('/outgoing/daringfireball.net/projects/markdown/syntax?referer=');">markdown syntax</a>.  If you haven&#8217;t seen markdown before, it&#8217;s a wiki-like syntax that is very easy to read and write, and can also be converted into a variety of formats easily, including HTML.  </p>
<p>In markdown, code blocks are simply lines that are separated from other lines by at least one blank line (or the start of the file) and are indented at least 4 spaces.</p>
<p><a href='http://naleid.com/blog/wp-content/uploads/2009/01/markdown_code.png'><img src="http://naleid.com/blog/wp-content/uploads/2009/01/markdown_code.png" alt="Markdown Screenshot Showing Code Indentation" title="markdown_code" width="700"  class="alignnone size-full wp-image-43" /></a></p>
<p>This is the script that I used to parse through the markdown file.  It uses a regular expression to find all of the code blocks in the markdown and then writes each of them to it&#8217;s own listing file.  Listing files were to be named consecutively from listing_1.txt through listing_n.txt.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#! /usr/bin/env groovy</span>
INPUT_START_OR_BLANK_LINE <span style="color: #669966;">=</span> /<span style="color: #669966;">&#40;</span><span style="color: #669966;">?</span>:\A<span style="color: #669966;">|</span>\n\n<span style="color: #669966;">&#41;</span>/
FOUR_SPACES_OR_TAB <span style="color: #669966;">=</span> /<span style="color: #669966;">&#40;</span><span style="color: #669966;">?</span>:<span style="color: #669966;">&#91;</span> <span style="color: #669966;">&#93;</span><span style="color: #669966;">&#123;</span><span style="color: #cc66cc;">4</span><span style="color: #669966;">&#125;</span><span style="color: #669966;">|</span>\t<span style="color: #669966;">&#41;</span>/
CODE <span style="color: #669966;">=</span> /.<span style="color: #669966;">*</span>\n<span style="color: #669966;">+</span>/
CODE_LINES <span style="color: #669966;">=</span> /<span style="color: #669966;">&#40;</span><span style="color: #669966;">?</span>:$FOUR_SPACES_OR_TAB$CODE<span style="color: #669966;">&#41;</span>/
LOOKAHEAD_FOR_NON_CODE_LINE <span style="color: #669966;">=</span> /<span style="color: #669966;">&#40;</span><span style="color: #669966;">?</span>:<span style="color: #669966;">&#40;</span><span style="color: #669966;">?=</span>^<span style="color: #669966;">&#91;</span> <span style="color: #669966;">&#93;</span><span style="color: #669966;">&#123;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">4</span><span style="color: #669966;">&#125;</span>\S<span style="color: #669966;">&#41;</span><span style="color: #669966;">|</span>\Z<span style="color: #669966;">&#41;</span>/
&nbsp;
<span style="color: #808080; font-style: italic;">// this regular expression will find all of the consecutive code lines in a markdown file</span>
<span style="color: #808080; font-style: italic;">// in a markdown file, if the line starts with a tab or at least 4 spaces, it's a code line</span>
<span style="color: #808080; font-style: italic;">// slightly modified from one in markdownj</span>
<span style="color: #808080; font-style: italic;">// see: http://github.com/myabc/markdownj/tree/master/src/java/com/petebevin/markdown/MarkdownProcessor.java</span>
MARKDOWN_CODE_BLOCK <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;(?m)&quot;</span> <span style="color: #669966;">+</span> 
                      <span style="color: #aa0000;">&quot;$INPUT_START_OR_BLANK_LINE&quot;</span> <span style="color: #669966;">+</span>
                      <span style="color: #aa0000;">&quot;($CODE_LINES+)&quot;</span> <span style="color: #669966;">+</span>
                      <span style="color: #aa0000;">&quot;$LOOKAHEAD_FOR_NON_CODE_LINE&quot;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> removeOldListings<span style="color: #669966;">&#40;</span>dir<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
    dir.<span style="color: #006600;">eachFileMatch</span><span style="color: #669966;">&#40;</span>~/.<span style="color: #669966;">*</span>listing_\d<span style="color: #669966;">+</span>\.<span style="color: #006600;">txt</span>/<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> file <span style="color: #669966;">-&gt;</span>
        <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;Removing $file&quot;</span>
        file.<span style="color: #006600;">delete</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>   
<span style="color: #669966;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> createListings<span style="color: #669966;">&#40;</span>file<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
    listingNumber <span style="color: #669966;">=</span> <span style="color: #cc66cc;">1</span>
    <span style="color: #669966;">&#40;</span>file.<span style="color: #006600;">text</span> <span style="color: #669966;">=</span>~ MARKDOWN_CODE_BLOCK<span style="color: #669966;">&#41;</span>.<span style="color: #663399;">each</span> <span style="color: #669966;">&#123;</span> full, codeBlock <span style="color: #669966;">-&gt;</span>
        <span style="color: #000000; font-weight: bold;">def</span> listing <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">File</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;listing_${(listingNumber++).toString().padLeft(3,'0')}.txt&quot;</span><span style="color: #669966;">&#41;</span> 
        <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;Creating $listing&quot;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// groovy's String.eachLine skips blank lines, but we want these in our source </span>
        <span style="color: #808080; font-style: italic;">// to make things more readable so we'll make our own eachLine</span>
        <span style="color: #669966;">&#40;</span>codeBlock <span style="color: #669966;">=</span>~ /.<span style="color: #669966;">*</span>/<span style="color: #669966;">&#41;</span>.<span style="color: #663399;">each</span> <span style="color: #669966;">&#123;</span> line <span style="color: #669966;">-&gt;</span>          
            <span style="color: #808080; font-style: italic;">// each markdown code block comes back with a tab or 4 spaces at the beginning, strip those off</span>
            <span style="color: #000000; font-weight: bold;">def</span> matcher <span style="color: #669966;">=</span> <span style="color: #669966;">&#40;</span>line <span style="color: #669966;">=</span>~ /$FOUR_SPACES_OR_TAB<span style="color: #669966;">&#40;</span>.<span style="color: #669966;">*</span><span style="color: #669966;">&#41;</span>/<span style="color: #669966;">&#41;</span>
            <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>matcher.<span style="color: #006600;">matches</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
                matcher.<span style="color: #663399;">find</span> <span style="color: #669966;">&#123;</span> fullLine, code <span style="color: #669966;">-&gt;</span>  listing <span style="color: #669966;">&lt;&lt;</span> <span style="color: #aa0000;">&quot;$code&quot;</span> <span style="color: #669966;">&#125;</span>
            <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #669966;">&#123;</span>
                listing <span style="color: #669966;">&lt;&lt;</span> <span style="color: #aa0000;">&quot;$line<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
            <span style="color: #669966;">&#125;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
removeOldListings<span style="color: #669966;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">File</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;.&quot;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span>
createListings<span style="color: #669966;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">File</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;article.markdown&quot;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Once I had all of those listing file, I used this script to execute each of the listing files and report whether any problems had occurred during the execution.  It uses the &#8220;eachFileMatch&#8221; method groovy adds to the File object, which you can give a regular expression pattern so that you can iterate over a targeted subset of files to process.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#! /usr/bin/env groovy</span>
<span style="color: #000000; font-weight: bold;">def</span> executeListings<span style="color: #669966;">&#40;</span>listingDir<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
    listingDir.<span style="color: #006600;">eachFileMatch</span><span style="color: #669966;">&#40;</span>~/.<span style="color: #669966;">*</span>listing_\d<span style="color: #669966;">+</span>\.<span style="color: #006600;">txt</span>/<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> listing <span style="color: #669966;">-&gt;</span>
        <span style="color: #663366;">print</span> <span style="color: #aa0000;">&quot;Executing $listing...&quot;</span>       
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">new</span> GroovyShell<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">evaluate</span><span style="color: #669966;">&#40;</span>listing<span style="color: #669966;">&#41;</span>
            <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;Success!&quot;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #669966;">&#40;</span>java.<span style="color: #006600;">lang</span>.<span style="color: #006600;">AssertionError</span> e<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;ERROR!&quot;</span>
            e.<span style="color: #006600;">printStackTrace</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>   
<span style="color: #669966;">&#125;</span>
&nbsp;
executeListings<span style="color: #669966;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">File</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;.&quot;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Just like a good set of unit tests, these scripts gave me the courage to make edits to my article, without needing to worry if I was breaking something or forgetting to make a change.  It&#8217;s a different kind of meta-programming when I can use regular expressions to help me write about using regular expressions :)</p>
<p><script type="text/javascript">var dzone_url = 'http://naleid.com/blog/2009/01/01/using-groovy-regular-expressions-to-parse-code-from-a-markdown-file/';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/01/01/using-groovy-regular-expressions-to-parse-code-from-a-markdown-file/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Groovy: Don&#8217;t Fear the RegExp</title>
		<link>http://naleid.com/blog/2008/05/19/dont-fear-the-regexp/</link>
		<comments>http://naleid.com/blog/2008/05/19/dont-fear-the-regexp/#comments</comments>
		<pubDate>Mon, 19 May 2008 05:32:42 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[groovy grails regexp]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=23</guid>
		<description><![CDATA[UPDATE: if you&#8217;re using Groovy 1.6.1 or greater (released April 2009), check out the new find and find all methods in this post.

Some people, when confronted with a problem, think &#8220;I know, I&#8217;ll use regular expressions!&#8221;
Now they have two problems. &#8212; Jaime Zawinski

There is a common and well-earned aversion in the Java world to regular [...]]]></description>
			<content:encoded><![CDATA[<p>UPDATE: if you&#8217;re using Groovy 1.6.1 or greater (released April 2009), <a href="http://naleid.com/blog/2009/04/07/groovy-161-released-with-new-find-and-findall-regexp-methods-on-string/">check out the new find and find all methods in this post</a>.</p>
<blockquote><p>
Some people, when confronted with a problem, think &#8220;I know, I&#8217;ll use regular expressions!&#8221;<br />
Now they have two problems. &#8212; <a href="http://www.jwz.org/" onclick="pageTracker._trackPageview('/outgoing/www.jwz.org/?referer=');">Jaime Zawinski</a>
</p></blockquote>
<p>There is a common and well-earned aversion in the Java world to regular expressions.  Prior to Java 1.4, regular expressions weren&#8217;t even part of the core language.  Post 1.4, using regular expressions is still a painful task of working with Pattern and Matcher objects.  Lots of typing is involved to make anything happen. It&#8217;s difficult enough that most Java devs don&#8217;t end up using them enough to actually remember how to read a regular expression, and they need to dig up the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html" onclick="pageTracker._trackPageview('/outgoing/java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html?referer=');">JavaDocs</a> (or cut and paste an old example), every time they want to use them.</p>
<p>This aversion has persisted into the Groovy community to a level that I haven&#8217;t seen in other dynamic scripting languages like Ruby, Python, and (obviously) Perl.  </p>
<p>The <a href="http://groovy.codehaus.org/Regular+Expressions" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Regular+Expressions?referer=');">current</a> <a href="http://docs.codehaus.org/display/GROOVY/Tutorial+5+-+Capturing+regex+groups" onclick="pageTracker._trackPageview('/outgoing/docs.codehaus.org/display/GROOVY/Tutorial+5+-+Capturing+regex+groups?referer=');">regexp</a> <a href="http://docs.codehaus.org/display/GROOVY/Tutorial+4+-+Regular+expressions+basics" onclick="pageTracker._trackPageview('/outgoing/docs.codehaus.org/display/GROOVY/Tutorial+4+-+Regular+expressions+basics?referer=');">docs</a> that pop up when doing a <a href="http://www.google.com/search?q=groovy+regular+expression" onclick="pageTracker._trackPageview('/outgoing/www.google.com/search?q=groovy+regular+expression&amp;referer=');">google search</a> are all outdated and don&#8217;t use any of the best techniques that are available in the groovy 1.5.X and 1.6-beta code that is now available.   The recent <a href="http://www.pragprog.com/titles/sdgrvr/groovy-recipes" onclick="pageTracker._trackPageview('/outgoing/www.pragprog.com/titles/sdgrvr/groovy-recipes?referer=');">Groovy Recipes</a> book doesn&#8217;t have an entry for regular expressions in the index, and I was unable to find a single example of a regular expression in the entire book.</p>
<p>This is unfortunate because Groovy makes using regular expressions <b>much</b> easier than in Java.  Under the covers, you&#8217;re still working with the same old Java Pattern and Matcher objects, but the Groovy syntax and additions to those classes are pleasant to work with.<br />
<span id="more-23"></span></p>
<h3>String Escaping with Slashy Strings</h3>
<p>Groovy adds a new type of string escaping, Slashy Strings, that can be used to make your regular expressions easier to read.  Forward slashes around text create String objects, just like quotes do.  Unlike quoted strings, you don&#8217;t have to escape backslashes with another backslash in a Slashy String:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">assert</span> java.<span style="color: #006600;">lang</span>.<span style="color: #aaaadd; font-weight: bold;">String</span> <span style="color: #669966;">==</span> /foo/.<span style="color: #000000; font-weight: bold;">class</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#40;</span> /Count is \d/ <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;Count is <span style="color: #000099; font-weight: bold;">\\</span>d&quot;</span> <span style="color: #669966;">&#41;</span></pre></div></div>

<p>You can also use groovy expressions Slashy Strings, just like double-quoted GStrings:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> name <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Ted Naleid&quot;</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#40;</span> /$name/ <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;Ted Naleid&quot;</span> <span style="color: #669966;">&#41;</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#40;</span> /$name/ <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;$name&quot;</span> <span style="color: #669966;">&#41;</span></pre></div></div>

<p>There isn&#8217;t anything specific to regular expressions with Slashy Strings, but many regular expressions use shorthand character classes such as \d (digit), \s (non-whitespace character), \b (word boundary) etc.  The JavaDocs for <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html" onclick="pageTracker._trackPageview('/outgoing/java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html?referer=');">Pattern</a> actually has a nice reference for regular expression character classes if you&#8217;re not familiar with them.</p>
<h3>Groovy Regular Expression Operators</h3>
<p>Groovy adds 3 new operators</p>
<ul>
<li> &#8220;<code>~</code>&#8221; &#8211; used before a string and it will cause the string to be compiled to a Pattern for later use</li>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// \b means word boundary, [A-Z] means any capital letter, + means one or more</span>
<span style="color: #808080; font-style: italic;">// so this matches any string of one or more capital letter with a word boundary (non-word character) on either side of it</span>
<span style="color: #000000; font-weight: bold;">def</span> shoutedWord <span style="color: #669966;">=</span> ~/\b<span style="color: #669966;">&#91;</span>A<span style="color: #669966;">-</span>Z<span style="color: #669966;">&#93;</span><span style="color: #669966;">+</span>\b/</pre></div></div>

<li> &#8220;<code>=~</code>&#8221; &#8211; Creates a Matcher out of the String on the left hand side and the Pattern on the right.</li>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> matcher <span style="color: #669966;">=</span> <span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;EUREKA&quot;</span> <span style="color: #669966;">=</span>~ shoutedWord<span style="color: #669966;">&#41;</span>  
<span style="color: #000000; font-weight: bold;">assert</span> matcher.<span style="color: #006600;">matches</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>         <span style="color: #808080; font-style: italic;">// TRUE</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> numberMatcher <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;1234&quot;</span> <span style="color: #669966;">=</span>~ /\d<span style="color: #669966;">+</span>/  
<span style="color: #000000; font-weight: bold;">assert</span> numberMatcher.<span style="color: #006600;">matches</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>   <span style="color: #808080; font-style: italic;">// TRUE</span></pre></div></div>

<li> &#8220;<code>==~</code>&#8221; &#8211; Returns a boolean that specifies if the full String matches the Pattern</li>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;1234&quot;</span> <span style="color: #669966;">==</span>~ /\d<span style="color: #669966;">+</span>/    <span style="color: #808080; font-style: italic;">// TRUE</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;FOO2&quot;</span> <span style="color: #669966;">==</span>~ /\d<span style="color: #669966;">+</span>/    <span style="color: #808080; font-style: italic;">// FALSE!!!</span></pre></div></div>

</ul>
<h3>Enhancements to the String Class</h3>
<p>In Groovy, the String class has been enhanced with a few &#8220;replace*&#8221; methods that allow you to leverage regular expressions.  These methods originally come from the Matcher class, but attaching them directly to String puts them right at your fingertips.</p>
<p><code>replaceFirst</code> will replace the first substring matched by a regular expression within the specified String:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;Green Eggs and Spam&quot;</span> <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;Spam Spam&quot;</span>.<span style="color: #006600;">replaceFirst</span><span style="color: #669966;">&#40;</span>/Spam/, <span style="color: #aa0000;">&quot;Green Eggs and&quot;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p><code>replaceAll</code> will replace all matching substrings within the specified String:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;The armor was colored silver&quot;</span> <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;The armour was coloured silver&quot;</span>.<span style="color: #006600;">replaceAll</span><span style="color: #669966;">&#40;</span>/ou/, <span style="color: #aa0000;">&quot;o&quot;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>There is an alternate version of <code>replaceAll</code> that takes a closure for the second parameter.  This is especially useful in the situations where you want to manipulate the matched value, or groups within the match to dynamically determine the replacement text.</p>
<p>For example, if we wanted to be able to turn a dashed phrase (&#8220;foo-bar&#8221;) into a camel case word (&#8220;fooBar&#8221;) we can&#8217;t just remove all dash characters, we also need to make the first letter after the dash capitalized (the &#8220;B&#8221; in &#8220;fooBar&#8221;).  </p>
<p>To do this, we can use a regular expression that captures the first letter after a dash in a group using parenthesis.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> dashedToCamelCase<span style="color: #669966;">&#40;</span>orig<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
	<span style="color: #808080; font-style: italic;">// regular expression is a dash, followed by parenthesis that form a group where we hold the word's first character</span>
    orig.<span style="color: #006600;">replaceAll</span><span style="color: #669966;">&#40;</span>/<span style="color: #669966;">-</span><span style="color: #669966;">&#40;</span>\w<span style="color: #669966;">&#41;</span>/<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> fullMatch, firstCharacter <span style="color: #669966;">-&gt;</span> firstCharacter.<span style="color: #006600;">toUpperCase</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;firstName&quot;</span> <span style="color: #669966;">==</span> dashedToCamelCase<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;first-name&quot;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;oneTwoThreeFourFiveSixSevenEight&quot;</span> <span style="color: #669966;">==</span> dashedToCamelCase<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;one-two-three-four-five-six-seven-eight&quot;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Using the version of <code>replaceAll</code> that takes a closure gives us a chance to manipulate the first character of the word and capitalize it.  This closure is always passed the full matched text of the regular expression as the first value, and then any groups as subsequent values.</p>
<p>Here we modify a phone number and keep the area code group, but replace the exchange and station number with hash marks:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;612-###-####&quot;</span> <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;612-555-1212&quot;</span>.<span style="color: #006600;">replaceAll</span><span style="color: #669966;">&#40;</span>/<span style="color: #669966;">&#40;</span>\d<span style="color: #669966;">&#123;</span><span style="color: #cc66cc;">3</span><span style="color: #669966;">&#125;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">-</span><span style="color: #669966;">&#40;</span>\d<span style="color: #669966;">&#123;</span><span style="color: #cc66cc;">3</span><span style="color: #669966;">&#125;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">-</span><span style="color: #669966;">&#40;</span>\d<span style="color: #669966;">&#123;</span><span style="color: #cc66cc;">4</span><span style="color: #669966;">&#125;</span><span style="color: #669966;">&#41;</span>/<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> fullMatch, areaCode, exchange, stationNumber <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> fullMatch <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;612-555-1212&quot;</span> 
    <span style="color: #000000; font-weight: bold;">assert</span> areaCode <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;612&quot;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> exchange <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;555&quot;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> stationNumber <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;1212&quot;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;$areaCode-###-####&quot;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<h3>Enhancements to Collections</h3>
<p>Groovy also makes significant additions to what you can do with Collections.  In addition to each, collect, inject, etc, there is a regular expression aware iterator called <a href="http://groovy.codehaus.org/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#grep(java.lang.Object,%20java.lang.Object)" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html_grep_java.lang.Object_20java.lang.Object?referer=');"><code>grep</code></a> that will pass each item in the Collection through a filter and return a subset of items that match the filter.  We can use a regular expression as a filter:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// regular expression says 0 or more characters (&quot;.*&quot;) followed by the string &quot;bar&quot; that is at the end of the string (&quot;$&quot;)</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;foobar&quot;</span>, <span style="color: #aa0000;">&quot;bazbar&quot;</span><span style="color: #669966;">&#93;</span> <span style="color: #669966;">==</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;foobar&quot;</span>, <span style="color: #aa0000;">&quot;bazbar&quot;</span>, <span style="color: #aa0000;">&quot;barquux&quot;</span><span style="color: #669966;">&#93;</span>.<span style="color: #663399;">grep</span><span style="color: #669966;">&#40;</span>~/.<span style="color: #669966;">*</span>bar$/<span style="color: #669966;">&#41;</span></pre></div></div>

<p>You can achieve the same thing with <a href="http://groovy.codehaus.org/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#findAll(java.util.Collection,%20groovy.lang.Closure)" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html_findAll_java.util.Collection_20groovy.lang.Closure?referer=');">findAll</a> but it takes a little more typing:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;foobar&quot;</span>, <span style="color: #aa0000;">&quot;bazbar&quot;</span><span style="color: #669966;">&#93;</span> <span style="color: #669966;">==</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;foobar&quot;</span>, <span style="color: #aa0000;">&quot;bazbar&quot;</span>, <span style="color: #aa0000;">&quot;barquux&quot;</span><span style="color: #669966;">&#93;</span>.<span style="color: #663399;">findAll</span> <span style="color: #669966;">&#123;</span> it <span style="color: #669966;">==</span>~ /.<span style="color: #669966;">*</span>bar$/ <span style="color: #669966;">&#125;</span></pre></div></div>

<h3>Working with Matchers</h3>
<p>As we&#8217;ve seen, using the <code>=~</code> operator will return a Matcher object.  Many of the existing regular expression examples on the web work by treating the Matcher as a list and getting the first (zero-based) element out of the list:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> matcher <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;foobazaarquux&quot;</span> <span style="color: #669966;">=</span>~ <span style="color: #aa0000;">&quot;o(b.*r)q&quot;</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;obazaarq&quot;</span>, <span style="color: #aa0000;">&quot;bazaar&quot;</span><span style="color: #669966;">&#93;</span> <span style="color: #669966;">==</span> matcher<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #669966;">&#93;</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;bazaar&quot;</span> <span style="color: #669966;">==</span> matcher<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #669966;">&#93;</span><span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #669966;">&#93;</span> <span style="color: #808080; font-style: italic;">// get the first grouping of the first map</span></pre></div></div>

<p>This is a little fragile as matcher[0] will throw an error if there was not actually a match.  Calling <code>matches()</code> doesn&#8217;t help as matches only checks if the regular expression matches the WHOLE string:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;foobazaarquux&quot;</span> <span style="color: #669966;">=</span>~ <span style="color: #aa0000;">&quot;o(b.*r)q&quot;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">matches</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>  <span style="color: #808080; font-style: italic;">// returns false!</span>
<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;foobazaarquux&quot;</span> <span style="color: #669966;">=</span>~ <span style="color: #aa0000;">&quot;.*(b.*r).*&quot;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">matches</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>  <span style="color: #808080; font-style: italic;">// returns true, &quot;.*&quot; matches 0 or more chars of any type</span></pre></div></div>

<p>You can check <code>getCount()</code> to see how many matches there were for some safety:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> m <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;foobar&quot;</span> <span style="color: #669966;">=</span>~ /quux/
<span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>m.<span style="color: #006600;">getCount</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
	<span style="color: #808080; font-style: italic;">// example won't get here as &quot;quux&quot; doesn't exist in &quot;foobar&quot;, the count is 0</span>
        <span style="color: #663366;">println</span> m<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #669966;">&#93;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>A groovier way to work with Matchers leverages collection iterators and the built in closures that Groovy provides to them.  Matcher supports the <code>iterator()</code> method and with that, gets everything else that any groovy List or Collection would have, including <code>collect</code>, <code>inject</code>, <code>findAll</code>, etc.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> paragraph <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;&quot;&quot;
    Lorem ipsum dolor 12:30 AM sit amet, 
    consectetuer adipiscing 1:15 AM elit. 
    Nunc rutrum diam sagittis nisi 9:22 PM.
&quot;&quot;&quot;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> HOUR <span style="color: #669966;">=</span> /<span style="color: #cc66cc;">10</span><span style="color: #669966;">|</span><span style="color: #cc66cc;">11</span><span style="color: #669966;">|</span><span style="color: #cc66cc;">12</span><span style="color: #669966;">|</span><span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #669966;">-</span><span style="color: #cc66cc;">9</span><span style="color: #669966;">&#93;</span>/
<span style="color: #000000; font-weight: bold;">def</span> MINUTE <span style="color: #669966;">=</span> /<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #669966;">-</span><span style="color: #cc66cc;">5</span><span style="color: #669966;">&#93;</span><span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #669966;">-</span><span style="color: #cc66cc;">9</span><span style="color: #669966;">&#93;</span>/
<span style="color: #000000; font-weight: bold;">def</span> AM_PM <span style="color: #669966;">=</span> /AM<span style="color: #669966;">|</span>PM/
<span style="color: #000000; font-weight: bold;">def</span> time <span style="color: #669966;">=</span> /<span style="color: #669966;">&#40;</span>$HOUR<span style="color: #669966;">&#41;</span>:<span style="color: #669966;">&#40;</span>$MINUTE<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#40;</span>$AM_PM<span style="color: #669966;">&#41;</span>/
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;12:30 AM&quot;</span>, <span style="color: #aa0000;">&quot;1:15 AM&quot;</span>, <span style="color: #aa0000;">&quot;9:22 PM&quot;</span><span style="color: #669966;">&#93;</span> <span style="color: #669966;">==</span> <span style="color: #669966;">&#40;</span>paragraph <span style="color: #669966;">=</span>~ time<span style="color: #669966;">&#41;</span>.<span style="color: #663399;">collect</span> <span style="color: #669966;">&#123;</span> it <span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;12:30 AM&quot;</span>, <span style="color: #aa0000;">&quot;1:15 AM&quot;</span><span style="color: #669966;">&#93;</span> <span style="color: #669966;">==</span> <span style="color: #669966;">&#40;</span>paragraph <span style="color: #669966;">=</span>~ time<span style="color: #669966;">&#41;</span>.<span style="color: #663399;">grep</span><span style="color: #669966;">&#40;</span>~/.<span style="color: #669966;">*</span>AM$/<span style="color: #669966;">&#41;</span></pre></div></div>

<p>A limitation of the iterator-based methods is that they don&#8217;t give you access to the individual groups (hour, minute, am/pm), just the full matched string (&#8220;12:30 AM&#8221;).  The <code>each</code> method is more powerful because as it iterates through, it passes the full match as well as each of the individual groups into the closure.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;foo1 bar30 foo27 baz9 foo600&quot;</span> <span style="color: #669966;">=</span>~ /foo<span style="color: #669966;">&#40;</span>\d<span style="color: #669966;">+</span><span style="color: #669966;">&#41;</span>/<span style="color: #669966;">&#41;</span>.<span style="color: #663399;">each</span> <span style="color: #669966;">&#123;</span> match, digit <span style="color: #669966;">-&gt;</span> <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;+$digit&quot;</span> <span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// result:</span>
<span style="color: #808080; font-style: italic;">// +1</span>
<span style="color: #808080; font-style: italic;">// +27</span>
<span style="color: #808080; font-style: italic;">// +600</span></pre></div></div>

<p>Another example (using the paragraph and time Matcher from above) showing how to pretty print all of the timestamps:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">&nbsp;
<span style="color: #669966;">&#40;</span>paragraph <span style="color: #669966;">=</span>~ time<span style="color: #669966;">&#41;</span>.<span style="color: #663399;">each</span> <span style="color: #669966;">&#123;</span>match, hour, minute, amPm <span style="color: #669966;">-&gt;</span> 
    <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;$hour:$minute ${amPm == 'AM' ? 'this morning' : 'this evening' }&quot;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// result: </span>
<span style="color: #808080; font-style: italic;">// 12:30 this morning</span>
<span style="color: #808080; font-style: italic;">// 1:15 this morning</span>
<span style="color: #808080; font-style: italic;">// 9:22 this evening</span></pre></div></div>

<p>Regular expressions are a powerful tool that Groovy makes as accessible as any other top-tier scripting language.  Using techniques to break more complicated regular expressions into their component pieces can make them much more readable (as in the time example above).</p>
<p>If you&#8217;re doing any sort of string processing beyond a simple <code>contains</code> or <code>split</code>, regular expressions in groovy can turn mountains of Java into a couple of lines of code.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2008/05/19/dont-fear-the-regexp/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Unit Testing Isolated Methods with Groovy</title>
		<link>http://naleid.com/blog/2008/03/24/unit-testing-isolated-methods-with-groovy/</link>
		<comments>http://naleid.com/blog/2008/03/24/unit-testing-isolated-methods-with-groovy/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 05:22:57 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://tednaleid.wordpress.com/?p=9</guid>
		<description><![CDATA[Glen Smith has been running a great series of posts this month to help people get started with unit testing. In that sprit, I thought I&#8217;d put out a post on some unit testing work that I&#8217;ve been doing recently.
There are a number of libraries and techniques for unit testing with groovy. It comes with [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blogs.bytecode.com.au/glen/" onclick="pageTracker._trackPageview('/outgoing/blogs.bytecode.com.au/glen/?referer=');">Glen Smith</a> has been running a <a href="http://blogs.bytecode.com.au/glen/2008/03/04/mockfor-march---overcoming-grails-testing-inertia.html" onclick="pageTracker._trackPageview('/outgoing/blogs.bytecode.com.au/glen/2008/03/04/mockfor-march---overcoming-grails-testing-inertia.html?referer=');">great</a> <a href="http://blogs.bytecode.com.au/glen/2008/03/07/mockfor-march---unit-testing-grails-taglibs.html" onclick="pageTracker._trackPageview('/outgoing/blogs.bytecode.com.au/glen/2008/03/07/mockfor-march---unit-testing-grails-taglibs.html?referer=');">series</a> of <a href="http://blogs.bytecode.com.au/glen/2008/03/12/mockfor-march---unit-testing-grails-controllers.html" onclick="pageTracker._trackPageview('/outgoing/blogs.bytecode.com.au/glen/2008/03/12/mockfor-march---unit-testing-grails-controllers.html?referer=');">posts</a> this month to help people get started with unit testing. In that sprit, I thought I&#8217;d put out a post on some unit testing work that I&#8217;ve been doing recently.</p>
<p>There are a number of libraries and techniques for unit testing with groovy. It comes with <a title="Untitled" href="http://groovy.codehaus.org/Groovy+Mocks" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Groovy+Mocks?referer=');">MockFor and StubFor</a> out of the box, and you can also leverage Java libraries like <a href="http://groovy.codehaus.org/Using+EasyMock+with+Groovy" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Using+EasyMock+with+Groovy?referer=');">EasyMock</a> and <a href="http://hamletdarcy.blogspot.com/2008/03/mockito-new-mock-framework-on-block.html" onclick="pageTracker._trackPageview('/outgoing/hamletdarcy.blogspot.com/2008/03/mockito-new-mock-framework-on-block.html?referer=');">Mockito</a> if your needs aren&#8217;t satisfied by the built-in constructs.</p>
<p>The mock and stub implementations that I mention above work well for allowing you to control the behavior of any collaborators, but what if your method calls another method within the same class? None of those solutions (as far as I&#8217;m aware) allow you to replace the behavior of other methods on the Class Under Test (CUT). If you are trying to unit test your method in true isolation, you need the ability to stub out the behavior of internal methods on the class (for example, to throw an exception to test try/catch logic).</p>
<p><span id="more-9"></span>If you had the following CUT:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> ClassUnderTest <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> testMe<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;${first()}, ${second()}&quot;</span>
    <span style="color: #669966;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">def</span> first<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;first&quot;</span>
    <span style="color: #669966;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">def</span> second<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;second&quot;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>If you&#8217;re trying to unit test the <code>testMe</code> method, you might want to control the values that come back from <code>first</code> and <code>second</code> to ensure that <code>testMe</code> still reacts as you expect.</p>
<p>This test helper class will allow you to test your methods in isolation, so you can focus on testing the logic in your Method Under Test (MUT), rather than worrying about the contortions that might be necessary to get helper methods into the state you want to test.</p>
<p><code>com.naleid.test.TestHelper.groovy:</code></p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #996600;">com.naleid.test</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> TestHelper <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">def</span> isolateMethod <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> methodRef, stubMethods, closure <span style="color: #669966;">-&gt;</span>
        <span style="color: #000000; font-weight: bold;">def</span> clazz <span style="color: #669966;">=</span> methodRef.<span style="color: #006600;">owner</span>.<span style="color: #006600;">theClass</span>
        clazz.<span style="color: #006600;">metaClass</span>.<span style="color: #663366;">invokeMethod</span> <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">String</span> name, args <span style="color: #669966;">-&gt;</span>
            <span style="color: #000000; font-weight: bold;">def</span> stubMethod <span style="color: #669966;">=</span> stubMethods<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span>
            <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>methodRef.<span style="color: #006600;">method</span> <span style="color: #669966;">==</span> name <span style="color: #669966;">||</span> stubMethod<span style="color: #669966;">?</span>.<span style="color: #006600;">owner</span> <span style="color: #669966;">==</span> clazz<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
                <span style="color: #808080; font-style: italic;">// invoke a real method on the class , it's either the method we're testing in isolation or</span>
                <span style="color: #808080; font-style: italic;">// one we've been told to pass through</span>
                <span style="color: #000000; font-weight: bold;">return</span> clazz.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">getMetaMethod</span><span style="color: #669966;">&#40;</span>name, args<span style="color: #669966;">&#41;</span>.<span style="color: #006600;">invoke</span><span style="color: #669966;">&#40;</span>delegate, args<span style="color: #669966;">&#41;</span>
            <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>stubMethod<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #808080; font-style: italic;">// we have a stub method to use</span>
                <span style="color: #000000; font-weight: bold;">return</span> stubMethods<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span>.<span style="color: #663366; font-weight: bold;">call</span><span style="color: #669966;">&#40;</span>args<span style="color: #669966;">&#41;</span>
            <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #669966;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Exception</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;Testing method in isolation; other method called that we haven't been provided a stub for: $name($args)&quot;</span><span style="color: #669966;">&#41;</span>
            <span style="color: #669966;">&#125;</span>
        <span style="color: #669966;">&#125;</span>
&nbsp;
        closure.<span style="color: #663366; font-weight: bold;">call</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #808080; font-style: italic;">// call the code that tests methodRef in isolation</span>
&nbsp;
        GroovySystem.<span style="color: #006600;">metaClassRegistry</span>.<span style="color: #006600;">removeMetaClass</span><span style="color: #669966;">&#40;</span>clazz<span style="color: #669966;">&#41;</span> <span style="color: #808080; font-style: italic;">// clean up after ourselves</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>What&#8217;s going on here? We&#8217;ve got a static method <code>isolateMethod</code> that allows us to pass in a method reference, a map of stub methods that we can control the behavior of, and a closure that will actually execute the tests while we have our method in isolation.   We temporarily modify the metaClass of our CUT so that we intercept all calls to it&#8217;s instances.  Then we execute the test closure that we were passed.  Finally, we clean up after ourselves by reverting our CUT&#8217;s metaClass back to it&#8217;s original state.</p>
<p>There is some similarity here to the <a href="http://groovy.codehaus.org/Using+MockFor+and+StubFor" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Using+MockFor+and+StubFor?referer=');"><code>use</code> keyword employed by MockFor and StubFor</a>.</p>
<p>Well, it&#8217;s probably easier to show rather than just tell. Here is a GroovyTestCase that uses the static <code>isolateMethod</code> to change the behavior of <code>first</code> and <code>second</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #996600;">com.naleid.test.TestHelper</span> <span style="color: #000000; font-weight: bold;">as</span> TH
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> IsolateMethodTests <span style="color: #000000; font-weight: bold;">extends</span> GroovyTestCase <span style="color: #669966;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> stubFirst <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;stubFirst&quot;</span> <span style="color: #669966;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">def</span> stubSecond <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;stubSecond&quot;</span> <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #993333;">void</span> testIsolateMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        assertEquals<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;first, second&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> ClassUnderTest<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">testMe</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span> <span style="color: #808080; font-style: italic;">// original behavior</span>
&nbsp;
        TH.<span style="color: #006600;">isolateMethod</span><span style="color: #669966;">&#40;</span>ClassUnderTest.<span style="color: #006600;">metaClass</span>.<span style="color: #669966;">&amp;</span>testMe, <span style="color: #669966;">&#91;</span>first: stubFirst, second: stubSecond<span style="color: #669966;">&#93;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            assertEquals<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;stubFirst, stubSecond&quot;</span>,  <span style="color: #000000; font-weight: bold;">new</span> ClassUnderTest<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">testMe</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span> <span style="color: #808080; font-style: italic;">// stubbed out method behavior</span>
        <span style="color: #669966;">&#125;</span>
&nbsp;
        assertEquals<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;first, second&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> ClassUnderTest<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">testMe</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span> <span style="color: #808080; font-style: italic;">// back to original behavior</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>We call the TestHelper&#8217;s <code>isolateMethod</code> and pass in the following items:</p>
<ul>
<li><code>ClassUnderTest.metaClass.&#038;testMe</code> &#8211; a reference to the <code>testMe</code> method that we get from ClassUnderTest&#8217;s metaClass</li>
<li><code>[first: stubFirst, second: stubSecond]</code> &#8211; a map of method names to stub closures that have replacement behavior for us to use</li>
</ul>
<p>We also give it a closure that shows that we&#8217;re using stub methods rather than the real methods.</p>
<p>What if you still want the behavior of some of the sub-methods that <code>testMe</code> calls?  All you have to do is pass in a reference to the real method and <code>isolateMethod</code> will pass it through.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #993333;">void</span> testIsolateMethodStubFirstRealSecond<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
    TH.<span style="color: #006600;">isolateMethod</span><span style="color: #669966;">&#40;</span>ClassUnderTest.<span style="color: #006600;">metaClass</span>.<span style="color: #669966;">&amp;</span>testMe, <span style="color: #669966;">&#91;</span>first: stubFirst, second: ClassUnderTest.<span style="color: #669966;">&amp;</span>second<span style="color: #669966;">&#93;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        assertEquals<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;stubFirst, second&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> ClassUnderTest<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">testMe</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p><code>isolateMethod</code> is also designed to throw an exception if a method that you haven&#8217;t given a stub is called by the MUT.   Here is an example that shows what happens where we&#8217;ve given <code>first</code>, but neglected to include a stub for <code>second</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #993333;">void</span> testIsolateMethodThrowsExceptionForMissingMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
    TH.<span style="color: #006600;">isolateMethod</span><span style="color: #669966;">&#40;</span>ClassUnderTest.<span style="color: #006600;">metaClass</span>.<span style="color: #669966;">&amp;</span>testMe, <span style="color: #669966;">&#91;</span>first: stubFirst<span style="color: #669966;">&#93;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> e <span style="color: #669966;">=</span> shouldFailWithCause<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">Exception</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">new</span> ClassUnderTest<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">testMe</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
    assertEquals<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;Testing method in isolation; other method called that we haven't been provided a stub for: second({})&quot;</span>, e.<span style="color: #006600;">toString</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>Using a technique like <code>isolateMethod</code> has the effect of making mocking libraries and unit testing much easier to work with, as you don&#8217;t need to worry about mocking out all of the collaborators that sub-methods of the MUT interact with.</p>
<p>I&#8217;m curious to hear how others have dealt with this issue in their unit testing in the past.  Are there other solutions out there that I&#8217;ve missed?</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2008/03/24/unit-testing-isolated-methods-with-groovy/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using the OSX Console.app to aid Grails Test Driven Development</title>
		<link>http://naleid.com/blog/2008/03/13/using-the-osx-consoleapp-to-aid-grails-test-driven-development/</link>
		<comments>http://naleid.com/blog/2008/03/13/using-the-osx-consoleapp-to-aid-grails-test-driven-development/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 05:24:25 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://tednaleid.wordpress.com/?p=3</guid>
		<description><![CDATA[With Groovy built-in, Grails is one of the best platforms running on the JVM for doing unit testing.
One limitation that it does have is that the current testing scripts seem to be oriented more towards creating test reports rather than giving the user the quick feedback that is helpful when doing Test Driven Development.
Here&#8217;s an [...]]]></description>
			<content:encoded><![CDATA[<p>With <a href="http://groovy.codehaus.org/" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/?referer=');">Groovy</a> built-in, <a href="http://grails.org/" onclick="pageTracker._trackPageview('/outgoing/grails.org/?referer=');">Grails</a> is one of the best platforms running on the JVM for doing unit testing.</p>
<p>One limitation that it does have is that the current testing scripts seem to be oriented more towards creating test reports rather than giving the user the quick feedback that is helpful when doing <a title="Test Driven Development (TDD)" href="http://en.wikipedia.org/wiki/Test-driven_development" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Test-driven_development?referer=');">Test Driven Development</a>.</p>
<p>Here&#8217;s an example of the output that you get on a failed test after running &#8220;grails test-app&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">-------------------------------------------------------
Running 1 Integration Test...
Running test BookTests...
testBookHasExpectedTitle...FAILURE
Integration Tests Completed in 622ms
-------------------------------------------------------
[junitreport] Transform time: 944ms
&nbsp;
Tests failed: 0 errors, 1 failures, 0 compilation errors. View reports in /Users/ted/Documents/workspace/foobar/test/reports</pre></div></div>

<p>Ok, that&#8217;s great&#8230;a test failed.  But why?  Where is the stacktrace and any output generated during the test?</p>
<p><span id="more-7"></span>As the output says, its down under test/reports.  Once you get there, you see that there are a number of different output files and formats, everything from xml files, standard error/out files, as well as plain output files.</p>
<p>Even for the tests that pass, Grails still puts an output file in the reports directory for it. When you start to accumulate a number of different unit tests, it can be a pain to find the right output file and load it up in something that lets you quickly figure out the source of the problem in that long, groovy stacktrace.</p>
<h3>Console.app and Aliases to the Rescue</h3>
<p>OSX comes with a utility called Console.app that is normally used to look at system logs.  It turns out that it&#8217;s also an excellent tool for looking at the output logs of Grails and for monitoring testing output when doing TDD.</p>
<p>OSX also allows you to launch any file (with the default file handler) from the command line with the &#8220;open&#8221; command.  If you use the &#8220;-a&#8221; switch, you can pass it the name of an application</p>
<p>Combining that with a little grep magic and a for loop allows us to identify all of the test output logs that actually had an error or a failure:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">oel</span>=<span style="color: #ff0000;">'for F in `grep -lE &quot;FAILED|ERROR&quot; test/reports/plain/*.txt`; do echo &quot;&gt;&gt;&gt; opening $F with Console&quot;; open -a Console.app $F; done;'</span></pre></div></div>

<p>If you stick that in your .profile all you have to after running &#8220;grails test-app&#8221; is type &#8220;oel&#8221; and any failing tests will automatically pop open in Console.app.</p>
<p><img src="http://naleid.com/blog/wp-content/uploads/2008/03/console.png" alt="Grails test-app log in Console.app" /></p>
<p>Once the console is open, you can use cmd-K to clear the console and shift-cmd-R to reload it.  The filtering abilities are also quite nice for finding relevant lines within the huge groovy stacktraces.  Just type the name of your class or package in the filter box (opt-shift-F) and it will only show you the lines that match your filter.</p>
<p><img src="http://naleid.com/blog/wp-content/uploads/2008/03/console_filter_lines.png" alt="Filtering out lines in Console.app" /></p>
<p>Alternatively, I like to switch from filtering lines out to highlighting the filter text.  This way, I can still see the surrounding stacktrace lines, but it&#8217;s easy to find the lines I actually care about.</p>
<p><img src="http://naleid.com/blog/wp-content/uploads/2008/03/console_highlight_lines.png" alt="Highlighting lines in Console.app" /></p>
<p>My days of using tail and less are over, but if you&#8217;re on a non-OSX platform, you can easily substitute one of these commands in the alias that you execute (if you&#8217;re on Windows, check out <a href="http://cygwin.com/" onclick="pageTracker._trackPageview('/outgoing/cygwin.com/?referer=');">cygwin</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2008/03/13/using-the-osx-consoleapp-to-aid-grails-test-driven-development/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
