<?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>Valtech UK &#187; TDD</title>
	<atom:link href="http://blog.valtech.co.uk/category/tdd/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.valtech.co.uk</link>
	<description>Aggregated works of Valtech UK consultants</description>
	<lastBuildDate>Mon, 30 Jan 2012 12:23:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Global Day of Code Retreat 2011 &#8211; London, UK</title>
		<link>http://blog.valtech.co.uk/craftsmanship/global-day-of-code-retreat-2011-london-uk/</link>
		<comments>http://blog.valtech.co.uk/craftsmanship/global-day-of-code-retreat-2011-london-uk/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 12:00:36 +0000</pubDate>
		<dc:creator>Oliver Wickham</dc:creator>
				<category><![CDATA[Code Retreat]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://blog.valtech.co.uk/?p=1103</guid>
		<description><![CDATA[Tweet It is not often that you get the opportunity to get involved with an event on the scale of Global Day of Code Retreat (GDCR). On Saturday (3rd December, 2011) an estimated 2200 software developers gathered in more than 90 cities around the world to solve a relatively simple computing problem. The objective was [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.valtech.co.uk%2Fcraftsmanship%2Fglobal-day-of-code-retreat-2011-london-uk%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://blog.valtech.co.uk/craftsmanship/global-day-of-code-retreat-2011-london-uk/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://blog.valtech.co.uk/craftsmanship/global-day-of-code-retreat-2011-london-uk/"  data-text="Global Day of Code Retreat 2011 &#8211; London, UK" data-count="horizontal" data-via="valtech">Tweet</a>
			</div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><h3></h3>
<p>It is not often that you get the opportunity to get involved with an event on the scale of Global Day of Code Retreat (GDCR). On Saturday (3rd December, 2011) an estimated 2200 software developers gathered in more than 90 cities around the world to solve a relatively simple computing problem. The objective was to implement <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway&#8217;s game of Life</a>.</p>
<p>The game has a simple set of rules, and has been implemented countless times since its creation in 1970. You might ask why it takes 2200 developers to solve this problem. There might be a clue in the method used to solve the problem &#8230;</p>
<p>&nbsp;</p>
<h2><strong>The Process</strong></h2>
<p>At a code retreat, the participants are divided into pairs, and attempt to implement the game in a 45 minute time slot. The twist is that even the fastest coders will not get to the end of the challenge in that time. Once the allotted 45 minutes expires, the whole process starts again &#8211; another 6 times. You might be thinking, why would anybody do this? Why would 2200 developers do this? Starting at 8:45am on a Saturday morning!?</p>
<p>Another clue is that the London event was organised by the London Software Craftsmanship Community (LSCC). The London chapter is part of a global movement of software craftsman who believe that:</p>
<p><em>&#8220;As aspiring Software Craftsmen we are raising the bar of professional software development by practicing it and helping others learn the craft&#8221;</em></p>
<p>[Taken from the <a href="http://manifesto.softwarecraftsmanship.org/">Software Craftsmanship Manifesto</a>]</p>
<p>So then, the GDRC is about repeating the same exercise several times in a day and the LSCC believe that helping others improves the craft. Armed with this information it becomes clear that Conway&#8217;s game of life is not the aim of the exercise, just a means to an end. Indeed once each session is finished the code is deleted &#8211; erased with no trace. It is the journey of developing a piece of code six times in succession that stops the participant from being focused on completing the exercise, and allows the focus to shift to the <strong><em>process</em></strong> of writing the code. To draw parallels with meditation is perhaps a stretch, but it does allow an opportunity to be more reflective about the code being written.</p>
<p>&nbsp;</p>
<h2><strong>Constraints</strong></h2>
<p>Each time the exercise is repeated, different constraints are added to the development process. This forces the pair to consider a different strategy for implementation of the problem.  Amongst the constraints used are: 4-rules-simple-design; object calisthenics and mute. The easiest to explain is mute, which mandates no communication between the pair developing the software, with the exception of the code written. This communication ban forces the developer to produce code where the intention is clear &#8211; so called ‘self documenting code’.</p>
<p>&nbsp;</p>
<h2><strong>Global Community</strong></h2>
<p>The Code Retreat day is repeated by isolated groups throughout the year. The idea of the Global Day of Code is to build a bigger community with more participants, have some fun, and to generate some publicity. With the event being run during a weekend, it is a great opportunity to meet a broad spectrum of people outside of your usual work team.</p>
<p>In practical terms, this meant sharing information with other events using twitter (#gdcr11), and three video conference sessions. It turns out that connecting two remote rooms full of software developers in meaningful exchange has its own challenges, both in terms of technology and raucousness!</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2 style="text-align: center;"><a href="http://blog.valtech.co.uk/wp-content/uploads/2011/12/IMG_06791.jpg"><img class="size-full wp-image-1139 aligncenter" title="Global Day of Code Retreat" src="http://blog.valtech.co.uk/wp-content/uploads/2011/12/IMG_06791.jpg" alt="" width="261" height="261" /></a></h2>
<p style="text-align: center;"><a href="http://blog.valtech.co.uk/wp-content/uploads/2011/12/IMG_0680.jpg"><img class="size-full wp-image-1127 aligncenter" title="Global Day of Code Retreat" src="http://blog.valtech.co.uk/wp-content/uploads/2011/12/IMG_0680.jpg" alt="" width="260" height="260" /></a></p>
<p style="text-align: center;">For more pictures, visit our Facebook Page:<a href="http://www.facebook.com/media/set/?set=a.256942401032375.62896.176314019095214&amp;type=3&amp;l=961e5c4378"> www.facebook.com/ValtechUK</a></p>
<h2></h2>
<p>&nbsp;</p>
<h2><strong>Free to Enter</strong></h2>
<p>The code retreat is run by volunteers, and paid for by sponsors. <a title="Valtech" href="http://twitter.com/#!/valtech">Valtech</a> is proud to have hosted and sponsored the LSCC Code Retreat in our London office because we fundamentally believe in the principles of software craftsmanship. A big thank you is due to Corey Haines, who was one of the originators of the Code Retreat concept and chief organiser of the Global Day of Code Retreat.</p>
<p>Also thanks to Sandro Mancuso and Samir Talwar from the LSCC for facilitating the event. The smooth running of the London event is in no small part due to Valtech&#8217;s own Maria Lacher for a marvellous effort co-ordinating the essentials such as food and venue.</p>
<h4> I look forward to Global Day of Code Retreat &#8217;12 – with experience gained from GDCR’11, it  should be the biggest and best yet!</h4>
<p>&nbsp;</p>
<h2>Video</h2>
<p><iframe src="http://player.vimeo.com/video/34129435?loop=1" width="625" height="469" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />
<a href="http://www.meetup.com/london-software-craftsmanship/">http://www.meetup.com/london-software-craftsmanship/</a></p>
<p>Samir&#8217;s in-depth overview of the event (warning – contains code!):</p>
<p><a href="http://coderetreat.org/profiles/blogs/global-day-of-coderetreat-an-account-from-london">http://coderetreat.org/profiles/blogs/global-day-of-coderetreat-an-account-from-london</a></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.valtech.co.uk/craftsmanship/global-day-of-code-retreat-2011-london-uk/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Readable Tests: Separating intent from implementation</title>
		<link>http://blog.valtech.co.uk/craftsmanship/readable-tests-separating-intent-from-implementation/</link>
		<comments>http://blog.valtech.co.uk/craftsmanship/readable-tests-separating-intent-from-implementation/#comments</comments>
		<pubDate>Fri, 10 Dec 2010 00:41:00 +0000</pubDate>
		<dc:creator>Sandro Mancuso</dc:creator>
				<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[fluent]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Very recently, I was working on a test class like this:public class AnalyticsExpirationDateManagerTest extends TestCase { private static final long ONE_HOUR_TIMEOUT = 1000 * 60 * 60; private static final long TWO_HOUR_TIMEOUT = ONE_HOUR_TIMEOUT * 2;  p...]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.valtech.co.uk%2Fcraftsmanship%2Freadable-tests-separating-intent-from-implementation%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://blog.valtech.co.uk/craftsmanship/readable-tests-separating-intent-from-implementation/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://blog.valtech.co.uk/craftsmanship/readable-tests-separating-intent-from-implementation/"  data-text="Readable Tests: Separating intent from implementation" data-count="horizontal" data-via="valtech">Tweet</a>
			</div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>
This article is packed full of code examples. For this reason it does not render nicely on our front page. To read the article please follow the link below.</p>
<p>
<span id="more-410"></span></p>
<p>Very recently, I was working on a test class like this:</p>
<pre class="brush:java">public class AnalyticsExpirationDateManagerTest extends TestCase {

 private static final long ONE_HOUR_TIMEOUT = 1000 * 60 * 60; private static final long TWO_HOUR_TIMEOUT = ONE_HOUR_TIMEOUT * 2;

 private Map&lt;Parameter, Long&gt; analyticsToTimeout; private long defaultTimeout;

 private Parameter minTimeoutParam; @Mock private CacheKeyImpl&lt;Parameter&gt; cacheKey;

    @Override    protected void setUp() throws Exception {     MockitoAnnotations.initMocks(this);

     this.minTimeoutParam = new Parameter("minTimeout", "type");

     when(cacheKey.getFirstKey()).thenReturn(minTimeoutParam);

     this.analyticsToTimeout = new HashMap&lt;Parameter, Long&gt;();     this.defaultTimeout = 0;    }

 public void testGetExpirationDateWhenAnalyticsToTimeoutsAndCacheKeyAreEmpty() {  AnalyticsExpirationDateManager&lt;Long&gt; manager =     new AnalyticsExpirationDateManager&lt;Long&gt;(analyticsToTimeout, defaultTimeout);  Date date = manager.getExpirationDate(cacheKey, 0L);  assertNotNull(date); }

 public void  testGetExpirationDateWithMinimunTimeoutOfOneHour() {  this.analyticsToTimeout.put(this.minTimeoutParam, ONE_HOUR_TIMEOUT);  Collection&lt;Parameter&gt; cacheKeysWithMinTimeoutParam = new ArrayList&lt;Parameter&gt;();  cacheKeysWithMinTimeoutParam.add(this.minTimeoutParam);  when(this.cacheKey.getKeys()).thenReturn(cacheKeysWithMinTimeoutParam);

  AnalyticsExpirationDateManager&lt;Long&gt; manager =    new AnalyticsExpirationDateManager&lt;Long&gt;(analyticsToTimeout, defaultTimeout);  Date date = manager.getExpirationDate(cacheKey, 0L);

  assertNotNull(date);  Calendar expirationDate = Calendar.getInstance();  expirationDate.setTime(date);

  Calendar currentDate = Calendar.getInstance();

  // Check if expiration date is one hour ahead current date.   int expirationDateHour = expirationDate.get(Calendar.HOUR_OF_DAY);  int currentDateHour = currentDate.get(Calendar.HOUR_OF_DAY);  assertTrue(expirationDateHour - currentDateHour == 1); }

 public void  testGetExpirationDateWhenCacheKeyIsNullAndDefaultTimeoutIsOneHour() {  CacheKeyImpl&lt;Parameter&gt; NULL_CACHEKEY = null;  AnalyticsExpirationDateManager&lt;Long&gt; manager =    new AnalyticsExpirationDateManager&lt;Long&gt;(analyticsToTimeout, ONE_HOUR_TIMEOUT);  Date date = manager.getExpirationDate(NULL_CACHEKEY, 0L);

  assertNotNull(date);  Calendar expirationDate = Calendar.getInstance();  expirationDate.setTime(date);

  Calendar currentDate = Calendar.getInstance();

  // Check if expiration date hour is the same of current date hour.  // When cache key is null, system date and time is returned and default timeout is not used.  int expirationDateHour = expirationDate.get(Calendar.HOUR_OF_DAY);  int currentDateHour = currentDate.get(Calendar.HOUR_OF_DAY);  assertTrue(expirationDateHour - currentDateHour == 0); }

 public void  testGetExpirationDateWithDefaultTimeout() {  // Default timeout is used when no time out is specified.  Collection&lt;Parameter&gt; cacheKeysWithoutTimeoutParam = new ArrayList&lt;Parameter&gt;();  cacheKeysWithoutTimeoutParam.add(new Parameter("name", "type"));  when(this.cacheKey.getKeys()).thenReturn(cacheKeysWithoutTimeoutParam);

  AnalyticsExpirationDateManager&lt;Long&gt; manager =    new AnalyticsExpirationDateManager&lt;Long&gt;(analyticsToTimeout, ONE_HOUR_TIMEOUT);  Date date = manager.getExpirationDate(cacheKey, 0L);

  assertNotNull(date);  Calendar expirationDate = Calendar.getInstance();  expirationDate.setTime(date);

  Calendar currentDate = Calendar.getInstance();

  // Check if expiration date is one hour ahead current date.   int expirationDateHour = expirationDate.get(Calendar.HOUR_OF_DAY);  int currentDateHour = currentDate.get(Calendar.HOUR_OF_DAY);  assertTrue(expirationDateHour - currentDateHour == 1); }

 public void  testGetExpirationDateWhenMinTimeoutIsSetAfterCreation() {  AnalyticsExpirationDateManager&lt;Long&gt; manager =    new AnalyticsExpirationDateManager&lt;Long&gt;(analyticsToTimeout, ONE_HOUR_TIMEOUT);  manager.setExpirationTimeout(this.minTimeoutParam.getName(), TWO_HOUR_TIMEOUT);

  Date date = manager.getExpirationDate(cacheKey, 0L);

  assertNotNull(date);  Calendar expirationDate = Calendar.getInstance();  expirationDate.setTime(date);

  Calendar currentDate = Calendar.getInstance();

  // Check if expiration date is two hour ahead current date.   int expirationDateHour = expirationDate.get(Calendar.HOUR_OF_DAY);  int currentDateHour = currentDate.get(Calendar.HOUR_OF_DAY);  assertTrue("Error", expirationDateHour - currentDateHour == 2); }

}</pre>
<p>Quite frightening, isn&#8217;t it? Very difficult to understand what&#8217;s going on there.</p>
<p>The class above covers 100% of the class under test and all the tests are valid tests, in terms of what is being tested.</p>
<p><span style="font-size: large;"><strong>Problems</strong></span></p>
<p>There are quite a few problems here:<br />
- The intent (what) and implementation (how) are mixed, making the tests very hard to read;<br />
- There is quite a lot of duplication among the test methods;<br />
- There is also a bug in the test methods when comparing dates, trying to figure out how many hours one date is ahead of the other. When running these tests in the middle of the day, they work fine. If running them between 22:00hs and 00:00hs, they break. The reason is that the hour calculation does not take into consideration the day.</p>
<p><span style="font-size: large;"><strong>Making the tests more readable</strong></span></p>
<p>Besides testing the software, tests should also be seen as documentation, where business rules are clearly specified. Since the tests here are quite messy, understanding the intention and detecting bugs can be quite difficult.</p>
<p>I&#8217;ve done quite a few refactorings to this code in order to make it more readable, always working in small steps and constantly re-running the tests after each change. I&#8217;ll try to summarise my steps for clarity and brevity.</p>
<p><strong>1. Fixing the hour calculation bug</strong></p>
<p>One of the first things that I had to do was to fix the hour calculation bug. In order to fix the bug across all test methods, I decided to extract the hour calculation into a separate class, removing all the duplication from the test methods. Using small steps, I took the opportunity to construct this new class called <em>DateComparator</em> (yes, I know I suck naming classes) using some internal Domain Specific Language (DSL) techniques.</p>
<pre class="brush: java">public class DateComparator {

 private Date origin; private Date target; private long milliseconds; private long unitsOfTime;

 private DateComparator(Date origin) {  this.origin = origin; }

 public static DateComparator date(Date origin) {  return new DateComparator(origin); }

 public DateComparator is(long unitsOfTime) {  this.unitsOfTime = unitsOfTime;  return this; }

 public DateComparator hoursAhead() {  this.milliseconds = unitsOfTime * 60 * 60 * 1000;  return this; }

 public static long hours(int hours) {  return hoursInMillis(hours); }

 private static long hoursInMillis(int hours) {  return hours * 60 * 60 * 1000; }

 public boolean from(Date date) {  this.target = date;  return this.checkDifference(); }

 private boolean checkDifference() {  return (origin.getTime() - target.getTime() &gt;= this.milliseconds); }}</pre>
<p>So now, I can use it to replace the test logic in the test methods.</p>
<p><strong>2. Extracting details into a super class</strong></p>
<p>This step may seem a bit controversial at first, but can be an interesting approach for separating the <em>what</em> from <em>how</em>. The idea is to move tests set up, field declarations, initialisation logic, everything that is related to the test implementation (<em>how</em>) to a super class, leaving the test class just with the test methods (<em>what</em>).</p>
<p>Although this many not be a good OO application of the IS-A rule, I think this is a good compromise in order to achieve better readability in the test class.</p>
<p>NOTE: Logic can be moved to a super class, external classes (helpers, builders, etc) or both.</p>
<p>Here is the super class code:</p>
<pre class="brush: java">public abstract class BaseTestForAnalyticsExperationDateManager extends TestCase {

 protected Parameter minTimeoutParam; @Mock protected CacheKeyImpl&lt;Parameter&gt; cacheKey; protected Date systemDate; protected CacheKeyImpl&lt;Parameter&gt; NULL_CACHEKEY = null; protected AnalyticsExpirationDateManager&lt;Long&gt; manager;

 @Override protected void setUp() throws Exception {  MockitoAnnotations.initMocks(this);  this.minTimeoutParam = new Parameter("minTimeout", "type");  when(cacheKey.getFirstKey()).thenReturn(minTimeoutParam);  this.systemDate = new Date(); }

 protected void assertThat(boolean condition) {  assertTrue(condition); }

 protected void addMinimunTimeoutToCache() {  this.configureCacheResponse(this.minTimeoutParam); }

 protected void doNotIncludeMinimunTimeoutInCache() {  this.configureCacheResponse(new Parameter("name", "type")); }

 private void configureCacheResponse(Parameter parameter) {  Collection&lt;Parameter&gt; cacheKeysWithMinTimeoutParam = new ArrayList&lt;Parameter&gt;();  cacheKeysWithMinTimeoutParam.add(parameter);  when(this.cacheKey.getKeys()).thenReturn(cacheKeysWithMinTimeoutParam); }}</pre>
<p><strong>3. Move creation and configuration of the object under test to a builder class</strong></p>
<p>The construction and configuration of the <em>AnalyticsExpirationDateManager</em> is quite verbose and adds a lot of noise to the test. Once again I&#8217;ll be using a builder class in order to make the code more readable and segregate responsibilities. Here is the builder class:</p>
<pre class="brush: java">public class AnalyticsExpirationDateManagerBuilder {

 protected static final long ONE_HOUR = 1000 * 60 * 60;

 protected Parameter minTimeoutParam; private AnalyticsExpirationDateManager&lt;Long&gt; manager; private Map&lt;Parameter, Long&gt; analyticsToTimeouts = new HashMap&lt;Parameter, Long&gt;(); protected long defaultTimeout = 0; private Long expirationTimeout; private Long minimunTimeout;

 private AnalyticsExpirationDateManagerBuilder() {  this.minTimeoutParam = new Parameter("minTimeout", "type"); }

 public static AnalyticsExpirationDateManagerBuilder aExpirationDateManager() {  return new AnalyticsExpirationDateManagerBuilder(); }

 public static long hours(int quantity) {  return quantity * ONE_HOUR; }

 public AnalyticsExpirationDateManagerBuilder withDefaultTimeout(long milliseconds) {  this.defaultTimeout = milliseconds;  return this; }

 public AnalyticsExpirationDateManagerBuilder withExpirationTimeout(long milliseconds) {  this.expirationTimeout = new Long(milliseconds);  return this; }

 public AnalyticsExpirationDateManagerBuilder withMinimunTimeout(long milliseconds) {  this.minimunTimeout = new Long(milliseconds);  return this; }

 public AnalyticsExpirationDateManager&lt;Long&gt; build() {  if (this.minimunTimeout != null) {   analyticsToTimeouts.put(minTimeoutParam, minimunTimeout);  }  this.manager = new AnalyticsExpirationDateManager(analyticsToTimeouts, defaultTimeout);  if (this.expirationTimeout != null) {   this.manager.setExpirationTimeout(minTimeoutParam.getName(), expirationTimeout);  }  return this.manager; }

}</pre>
<p><strong>The final version of the test class </strong></p>
<p>After many small steps, that&#8217;s how the test class looks like. I took the opportunity to rename the test methods as well.</p>
<pre class="brush: java">import static com.mycompany.AnalyticsExpirationDateManagerBuilder.*;import static com.mycompany.DateComparator.*;

public class AnalyticsExpirationDateManagerTest extends BaseTestForAnalyticsExperationDateManager {

 public void testExpirationTimeWithJustDefaultValues() {  manager = aExpirationDateManager().build();  Date cacheExpiration = manager.getExpirationDate(cacheKey, 0L);  assertThat(dateOf(cacheExpiration).is(0).hoursAhead().from(systemDate)); }

 public void  testExpirationTimeWithMinimunTimeoutOfOneHour() {     addMinimunTimeoutToCache();    manager = aExpirationDateManager()      .withMinimunTimeout(hours(1))      .build();  Date cacheExpiration = manager.getExpirationDate(cacheKey, 0L);  assertThat(dateOf(cacheExpiration).is(1).hoursAhead().from(systemDate)); }

 public void  testExpirationTimeWhenCacheKeyIsNullAndDefaultTimeoutIsOneHour() {  manager = aExpirationDateManager()      .withDefaultTimeout(hours(1))      .build();  Date cacheExpiration = manager.getExpirationDate(NULL_CACHEKEY, 0L);  // When cache key is null, system date and time is returned and default timeout is not used.  assertThat(dateOf(cacheExpiration).is(0).hoursAhead().from(systemDate)); }

 public void  testExpirationTimeWithDefaultTimeout() {  doNotIncludeMinimunTimeoutInCache();  manager = aExpirationDateManager()      .withDefaultTimeout(hours(1))      .build();  Date cacheExpiration = manager.getExpirationDate(cacheKey, 0L);  assertThat(dateOf(cacheExpiration).is(1).hoursAhead().from(systemDate)); }

 public void  testExpirationTimeWhenExpirationTimeoutIsSet() {  manager = aExpirationDateManager()      .withDefaultTimeout(hours(1))      .withExpirationTimeout(hours(2))      .build();  Date cacheExpiration = manager.getExpirationDate(cacheKey, 0L);  // Expiration timeout has precedence over default timeout.  assertThat(dateOf(cacheExpiration).is(2).hoursAhead().from(systemDate)); }

}</pre>
<p><span style="font-size: large;"><br />
</span><br />
<span style="font-size: large;"><strong>Conclusion</strong></span></p>
<p>Test classes should be easy to read. They should express intention, system behaviour, business rules. Test classes should express how the system works. They are executable requirements and specifications and should be a great source of information for any developer joining the project.</p>
<p>In order to achieve that, we need to try to keep our test methods divided in just 3 simple instructions.</p>
<p><strong>1. Context</strong>: The state of the object being tested. Here is where we set all the attributes and mock dependencies. Using variations of the Builder pattern can greatly enhance readability.</p>
<pre class="brush: java">manager = aExpirationDateManager()                .withDefaultTimeout(hours(1))                .withExpirationTimeout(hours(2))                .build();</pre>
<p><strong>2. Operation</strong>: The operation being tested. Here is where the operation is invoked.</p>
<pre class="brush: java">Date cacheExpiration = manager.getExpirationDate(cacheKey, 0L);</pre>
<p><strong>3. Assertion</strong>: Here is where you specify the behaviour expected. The more readable this part is, the better. Using DSL-style code is probably the best way to express the intent of the test.</p>
<pre class="brush: java">assertThat(dateOf(cacheExpiration).is(2).hoursAhead().from(systemDate));</pre>
<p>In this post I went backwards. I&#8217;ve started from a messy test class and refactored it to a more readable implementation. As many people now are doing TDD, I wanted to show how we can improve an existing test. For new tests, I would suggest that you start writing the tests following the <em>Context</em> &gt;&gt; <em>Operation</em> &gt;&gt; <em>Assertion</em> approach. Try writing the test code in plain English. Once the test intent is clear, start replacing the plain English text with Java internal DSL code, keeping the implementation out of the test class.</p>
<p><em>PS: The ideas for this blog post came from a few discussions I had during the Software Craftsmanship Round-table meetings promoted by the <a href="http://www.meetup.com/london-software-craftsmanship/">London Software Craftsmanship Community (LSCC).</a> </em></p>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/8424060401701893376-6729909628427981355?l=craftedsw.blogspot.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.valtech.co.uk/craftsmanship/readable-tests-separating-intent-from-implementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit tests, code coverage and the hidden trap&#8230;</title>
		<link>http://blog.valtech.co.uk/agile/unit-tests-code-coverage-and-the-hidden-trap/</link>
		<comments>http://blog.valtech.co.uk/agile/unit-tests-code-coverage-and-the-hidden-trap/#comments</comments>
		<pubDate>Fri, 30 Jul 2010 14:49:30 +0000</pubDate>
		<dc:creator>Jorge Migueis</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[coverage]]></category>
		<category><![CDATA[Unit test]]></category>

		<guid isPermaLink="false">http://blog.valtech.co.uk/?p=330</guid>
		<description><![CDATA[Tweet Quality has always been a &#8220;hot&#8221; subject in software engineering, and several good development practices used in Agile development, unit testing for example, have been created to improve the quality of the softwares developed. Programme Managers, Project Managers and Assurance Quality Managers haven&#8217;t just been looking for techniques to improve quality, they&#8217;ve also been [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.valtech.co.uk%2Fagile%2Funit-tests-code-coverage-and-the-hidden-trap%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://blog.valtech.co.uk/agile/unit-tests-code-coverage-and-the-hidden-trap/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://blog.valtech.co.uk/agile/unit-tests-code-coverage-and-the-hidden-trap/"  data-text="Unit tests, code coverage and the hidden trap&#8230;" data-count="horizontal" data-via="valtech">Tweet</a>
			</div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>Quality has always been a &#8220;hot&#8221; subject in software engineering, and several good development practices used in Agile development, unit testing for example, have been created to improve the quality of the softwares developed.</p>
<p>Programme Managers, Project Managers and Assurance Quality Managers haven&#8217;t just been looking for techniques to improve quality, they&#8217;ve also been looking for ways to monitor the quality of the projects and the application of these techniques.</p>
<p>This has lead to the development of numerous tools to check the unit testing coverage, the style of the code and its compliance to well accepted rules. Plus, of course, dashboards that gather all that information and present it in a user friendly way.</p>
<p>One of the most commonly used metrics is the code coverage of the unit tests. We often see in Agile teams rules like, &#8220;the line coverage should at least 80%&#8221;, or &#8220;the branch coverage should be at least 70%&#8221;. But&#8230;herein lies the hidden trap.<span id="more-330"></span><!--more-->The code coverage is not enough to verify the quality of the tests. Recently, I saw some unit tests that were exercising the code, but did not have real assertions. The test would only check that the data received was not nil. Something like:</p>
<p><code style="color: coral; text-align: left;"><br />
/**<br />
* Example of a useless test.<br />
* As Mashooq Badar explained in a previous entry<br />
* of this blog, tests should have explicit names.<br />
*/<br />
public void<br />
testThatTheCodeRunsWithoutCheckingTheReturnedValue() {<br />
// Prepare Context<br />
// create mock object for instance using Mockito<br />
AnInterfaceToMock mockObject =<br />
mock(AnInterfaceToMock.class);<br />
// Create instance of class under test<br />
// and inject mock objects<br />
ClassUnderTest anInstance = new ClassUnderTest();<br />
anInstance.setInterfaceToMock(mockObject);<br />
// Run code to test<br />
List result = anInstance.operationUnderTest();<br />
// Assertions<br />
assertNotNull(result);<br />
}</code></p>
<p>This test is almost useless, as it does not check the list of data it received. We do not know whether or not the &#8216;operationUnderTest&#8217; performed its job properly. The only thing this test shows is that the &#8216;operationUnderTest&#8217; did not throw up an exception. A change in the code of the class under test will probably not affect this test. However, the quality dashboard will present a healthy project with a high level of code coverage and instil a false confidence in the managers&#8217; minds. There is no tool that can perform that extra check, for now.</p>
<p>This is one of the reasons why code reviews have to be performed, published and monitored as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.valtech.co.uk/agile/unit-tests-code-coverage-and-the-hidden-trap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Naming your Unit Tests</title>
		<link>http://blog.valtech.co.uk/tdd/naming-your-unit-tests/</link>
		<comments>http://blog.valtech.co.uk/tdd/naming-your-unit-tests/#comments</comments>
		<pubDate>Thu, 27 May 2010 15:21:25 +0000</pubDate>
		<dc:creator>Mashooq Badar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://mashb.wordpress.com/?p=118</guid>
		<description><![CDATA[Often I see Unit Tests with the test methods that have the same name as the method under test prefixed with the word "test" e.g. testSubmitApplication. This provides no extra information on which "flow" of the mothod is being tested. Other test method names provide a bit more information by suffixing the nature of the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mashb.wordpress.com&#038;blog=7354608&#038;post=118&#038;subd=mashb&#038;ref=&#038;feed=1" />]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.valtech.co.uk%2Ftdd%2Fnaming-your-unit-tests%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://blog.valtech.co.uk/tdd/naming-your-unit-tests/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://blog.valtech.co.uk/tdd/naming-your-unit-tests/"  data-text="Naming your Unit Tests" data-count="horizontal" data-via="valtech">Tweet</a>
			</div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>Often I see Unit Tests with the test methods that have the same name as the method under test prefixed with the word &#8220;test&#8221; e.g. <code>testSubmitApplication</code>. This provides no extra information on which &#8220;flow&#8221; of the mothod is being tested. Other test method names provide a bit more information by suffixing the nature of the test e.g. <code>testSubmitApplicationWithInvalidCriteria</code>. It better but not much better. A number of IDEs actually allow the developer to generate test method names based on the class under test which in my opinion defeats the object.</p>
<p>Unit test methods should be named in such as way that they provide a clear description of the test. In my opinion the prefix &#8220;test&#8221; is redundent and should never appear in your test method names unless it is part of the domain vocabulary. For example <code>AppicationSubmittedWithInvalidCriteriaMustRaiseException</code>* is more informative then <code>testSubmitApplication</code>. Providing a more descriptive name also serves to keep a clear focus on the flow under test and leads the devloper to create a test method per flow.</p>
<p><em>*Please Note that the example method name is a simplification. I would consider the term &#8220;InvalidCriteria&#8221; a bit too high-level for a real unit test. It should be more specific such as <code>AppicationSubmittedWithNoSurnameMustRaiseException</code>.</em></p>
<p>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mashb.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mashb.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mashb.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mashb.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mashb.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mashb.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mashb.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mashb.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mashb.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mashb.wordpress.com/118/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mashb.wordpress.com&#038;blog=7354608&#038;post=118&#038;subd=mashb&#038;ref=&#038;feed=1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.valtech.co.uk/tdd/naming-your-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

