<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Marvellous Mechanical Mouse Organ &#187; Unit Testing</title>
	<atom:link href="http://fintanp.wordpress.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://fintanp.wordpress.com</link>
	<description>Start Braindump. Error: Brain not found.</description>
	<lastBuildDate>Thu, 15 Nov 2007 23:26:30 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='fintanp.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/29c36e7e4e2c551c9a59d0bc76a56d60?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>The Marvellous Mechanical Mouse Organ &#187; Unit Testing</title>
		<link>http://fintanp.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://fintanp.wordpress.com/osd.xml" title="The Marvellous Mechanical Mouse Organ" />
		<item>
		<title>Retrofitting Unit Tests Part 4 &#8211; Complex Test, Complex Code</title>
		<link>http://fintanp.wordpress.com/2007/11/02/retrofitting-unit-tests-part-4-complex-test-complex-code/</link>
		<comments>http://fintanp.wordpress.com/2007/11/02/retrofitting-unit-tests-part-4-complex-test-complex-code/#comments</comments>
		<pubDate>Fri, 02 Nov 2007 13:18:21 +0000</pubDate>
		<dc:creator>fintanp</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fintanp.wordpress.com/2007/11/02/retrofitting-unit-tests-part-4-complex-test-complex-code/</guid>
		<description><![CDATA[




Picture by Olivander
Some rights reserved.


Having introduced mock objects, even if you’ve managed to avoid the pitfalls described in the previous posts in this series, you can often end up with some pretty complex and ugly-looking unit tests.  There might be a lot of mock objects doing very little or there may be a lot [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=90&subd=fintanp&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><table class="image" align="left" width="180">
<tr>
<td><img width="180" src="http://fintanp.files.wordpress.com/2007/10/snow-mobile.jpg?w=180" alt="Snow Speeder" style="border:medium none;" /></td>
</tr>
<tr>
<td class="caption"><font color="gray" size="-2">Picture by <a href="http://flickr.com/photos/olivander/" target="_blank">Olivander</a><br />
<a href="http://creativecommons.org/licenses/by-nc-sa/2.0/" target="_blank"><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_attribution_small.gif" alt="Attribution" align="middle" /><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_noncomm_small.gif" alt="Non-Commercial" align="middle" /><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_sharealike_small.gif" alt="Share Alike" align="middle" /></a><a href="http://creativecommons.org/licenses/by-nc-sa/2.0/deed.en-us" target="_blank">Some rights reserved.</a></font></td>
</tr>
</table>
<p>Having introduced mock objects, even if you’ve managed to avoid the pitfalls described in the <a href="http://fintanp.wordpress.com/2007/10/19/retrofitting-unit-tests-part-2-when-a-unit-test-isnt/">previous</a> <a href="http://fintanp.wordpress.com/2007/10/23/retrofitting-unit-tests-part-3-mock-object-hell/">posts</a> in this series, you can often end up with some pretty complex and ugly-looking unit tests.  There might be a lot of mock objects doing very little or there may be a lot of configuration required for the test.  Fight the urge to blame the unit test though.  If the unit test is complex, chances are it&#8217;s because the underlying code is complex.</p>
<p>For example, you might find yourself creating multiple mock objects simply to reproduce this pattern;</p>
<pre>
    classA.getB().getC().getD().doSomethingWithD();
</pre>
<p><span id="more-90"></span>In order to mock the invocation of the class D method you end up with something that looks like this if you’re using EasyMock:</p>
<pre>
    A mockA = createMock(A.class);
    B mockB = createMock(B.class);
    C mockC = createMock(C.class);
    D mockD = createMock(D.class);

    expect(mockA.getB()).andReturn(mockB);
    expect(mockB.getC()).andReturn(mockC);
    expect(mockC.getD()).andReturn(mockD);
    expect(mockD.doSomethingWithD()).andReturn(true);
</pre>
<p>It gets worse if this pattern repeats itself throughout the code.  If it does though it’s probably a code smell and more than likely indicates some potential refactoring of the underlying code.  Apply the <a href="http://www.refactoring.com/catalog/removeMiddleMan.html" target="_blank">Remove Middle Man</a> refactoring and go to this:</p>
<pre>
    classA.doSomething();    // Delegates to doSomethingWithD
</pre>
<p>The setup for your mock object in your unit test reduces to:</p>
<pre>
    A mockA = createMock(A.class);
    expect(mockA.doSomething()).andReturn(true);
</pre>
<p>Refactoring as you go while implementing your tests will help reduce this kind of complexity but be careful! Without a unit test in place for regression testing you may actually introduce bugs without realising it.  The general rule for writing unit tests applies: get your test working, refactor the code a little, refactor the test a little and make sure nothing is broken.</p>
<p>Your best bet may be to get a working unit test regardless of how complex it is without any significant refactoring of the code under test and then refactor<sup>1</sup>.  This way you’ll have a test which can be used to do regression testing.  Later you can refactor the code being tested and you’ll then be able to refactor the test, simplifying that too.</p>
<p>Having said all that be very aware that you may be overcomplicating your test with your use of mocks and may end up hiding the real test in a pile of mock object expectations.  This is where the use of stubs as opposed to mocks can come in handy, especially if refactoring is not an option<sup>2</sup>.  Instead of creating a set of mock objects and setting up their expected method calls, you create stub versions of the collaborator classes which have canned responses to method invocations.  You might find that these can then be re-used throughout your tests, simplifying them greatly.</p>
<p>Using my previous example, we might create a stub version of A in the following way:</p>
<pre>
    public class StubA implements A {
        private B stubB;

        public StubA(B stubB) {
            this.stubB = stubB;
        }

        @Override
        public B getB() {
            return stubB;
        }

        // Other interface methods are implemented as well and
        // can either return dummy values or throw exceptions.
    }
</pre>
<p>This of course assumes that A is an interface or can be extended with all of it&#8217;s public methods being overridden.  Don&#8217;t forget that the whole point of the exercise is to test code in isolation of the actual implementation of A.  We just want our stub implementation to return dummy values or throw exceptions for methods we don&#8217;t want (or expect) to be called.</p>
<p>Assuming that the stub versions of B and C look something similar, the setup of our test now looks something like:</p>
<pre>
    // This is the only mock object - it's the
    // real thing we're looking to happen.
    D mockD = createMock(D.class);
    expect(mockD.doSomethingWithD()).andReturn(true);

    // Here come the stubs which just enable our test.
    A classA = new StubA(new StubB(new StubC(mockD))));
</pre>
<p>Now when the code under test does this&#8230;</p>
<pre>
    classA.getB().getC().getD().doSomethingWithD();
</pre>
<p>&#8230;our stubs will provide the mock object which will be invoked to do the real work.</p>
<p>The nice thing about this is that because we don&#8217;t care about how A, B and C get used we don&#8217;t have to create mock objects.  On top of that, if these objects are used in the same way in multiple tests then my stub implementations can be re-used making the whole test suite a lot simpler.</p>
<p>I reckon it&#8217;s largely a judgement call on when to use mocks or stubs and it&#8217;s one that probably only really comes with experience<sup>3</sup>.  In my mind though there’s nothing wrong with starting out with a complex unit test full of mock objects, refactoring the code and then refactoring the test to simplify it all, including replacing mock objects with stubs.</p>
<p>In the next part of this series I’ll show how complexity can also be a result of “engineered bugs”.</p>
<p>&#8211; Fintan</p>
<hr />1 &#8211; Assuming you can get the test working in the first place without refactoring.<br />
2 &#8211; The example in this post is based on some real-world code I&#8217;ve been looking at recently and is an obvious candidate for refactoring.  Your mileage may vary.<br />
3 &#8211; You weren&#8217;t expecting any easy answers were you?</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/fintanp.wordpress.com/90/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/fintanp.wordpress.com/90/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fintanp.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fintanp.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fintanp.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fintanp.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fintanp.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fintanp.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fintanp.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fintanp.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fintanp.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fintanp.wordpress.com/90/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=90&subd=fintanp&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://fintanp.wordpress.com/2007/11/02/retrofitting-unit-tests-part-4-complex-test-complex-code/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9fefd4a9c0730bf11295b7f5bc1f685d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fintanp</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/10/snow-mobile.jpg" medium="image">
			<media:title type="html">Snow Speeder</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_attribution_small.gif" medium="image">
			<media:title type="html">Attribution</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_noncomm_small.gif" medium="image">
			<media:title type="html">Non-Commercial</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_sharealike_small.gif" medium="image">
			<media:title type="html">Share Alike</media:title>
		</media:content>
	</item>
		<item>
		<title>Retrofitting Unit Tests Part 3 &#8211; Mock Object Hell</title>
		<link>http://fintanp.wordpress.com/2007/10/23/retrofitting-unit-tests-part-3-mock-object-hell/</link>
		<comments>http://fintanp.wordpress.com/2007/10/23/retrofitting-unit-tests-part-3-mock-object-hell/#comments</comments>
		<pubDate>Tue, 23 Oct 2007 09:39:56 +0000</pubDate>
		<dc:creator>fintanp</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fintanp.wordpress.com/2007/10/23/retrofitting-unit-tests-part-3-mock-object-hell/</guid>
		<description><![CDATA[




Picture by greefus groinks
Some rights reserved.


In the previous part of this series on retrofitting unit tests I talked about how you can break the unit-test as integration-test pattern by introducing mock objects.  Probably the best way to do this is by using one of the many mock object toolkits out there1 .  For [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=88&subd=fintanp&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><table class="image" align="left" width="180">
<tr>
<td><img src="http://fintanp.files.wordpress.com/2007/10/banged-up-spoiler.jpg?w=180" alt="Spoiler worth more than car" style="border:medium none;" width="180" /></td>
</tr>
<tr>
<td class="caption"><font color="gray" size="-2">Picture by <a href="http://www.flickr.com/photos/stinkypeter/" target="_blank">greefus groinks</a><br />
<a href="http://creativecommons.org/licenses/by-sa/2.0/" target="_blank"><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_attribution_small.gif" alt="Attribution" align="middle" /><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_sharealike_small.gif" alt="Share Alike" align="middle" /></a><a href="http://creativecommons.org/licenses/by-sa/2.0/deed.en-us" target="_blank">Some rights reserved.</a></font></td>
</tr>
</table>
<p>In the <a href="http://fintanp.wordpress.com/2007/10/19/retrofitting-unit-tests-part-2-when-a-unit-test-isnt/">previous part</a> of this series on retrofitting unit tests I talked about how you can break the unit-test as integration-test pattern by introducing <a href="http://en.wikipedia.org/wiki/Mock_object" target="_blank">mock objects</a>.  Probably the best way to do this is by using one of the many mock object toolkits out there<sup>1</sup> .  For Java development my preference is for <a href="http://www.easymock.org/" target="_blank">EasyMock</a> although there are plenty of others.</p>
<p>Introducing mock objects can cause their own set of headaches though and when retrofitting unit tests to existing code you’re likely to find a number of reasons why it can prove difficult or even impossible to introduce them.</p>
<p><span id="more-88"></span>The first and often hardest problem to get around is that the code to be tested is tightly-coupled with the dependency you’re trying to mock out.  If class A uses an instance of class B it’ll be impossible to mock that instance if it’s constructed somewhere inside class A.  You can get around this by doing a small amount of refactoring and introducing dependency injection but there could be the suspicion that you’re changing the design of your code to make it testable.</p>
<p>I really like dependency injection and inversion of control as general patterns but I realise that it’s something of a controversial subject.  The arguments for and against it are summed up well in <a href="http://martinfowler.com/articles/injection.html" target="_blank">Martin Fowler’s excellent piece</a> on the subject and there’s been an ongoing discussion on <a href="http://www.mockobjects.com" target="_blank">mockobjects.com</a> about it’s use in unit testing as well.  Some of the people I’ve spoken to who dislike DI feel that it breaks basic rules of encapsulation.  Personally I think you need to strike a balance between encapsulation and tight-coupling between objects.</p>
<p>Assuming you’re coding to interfaces I see no reason why you can’t inject the implementation to be used without breaking encapsulation.  If anything you’ll just be exposing your object’s contract with the rest of the system rather than how it works.  To add a bit of DI while avoiding having to change the way the object is used throughout the code you could add a package-scope constructor that sets the mock instance required.  By making it package-scope you&#8217;re limiting the scope for it to be used outside of the context of a unit test.  The drawback is that you&#8217;re now adding code purely for testing and your test will be bypassing the constructor used at runtime.</p>
<p>One alternative solution to dependency injection when you need to break tightly-coupled dependencies in unit tests is to use <a href="http://en.wikipedia.org/wiki/Aspect_oriented_programming" target="_blank">Aspects</a>.  You could create an Aspect to intercept invocations on particular methods, creating a kind of pseudo-mock. <a href="http://www.xprogramming.com/xpmag/virtualMockObjects.htm" target="_blank">This article</a> on <a href="http://www.xprogramming.com" target="_blank">xprogramming.com</a> has a good description of an implementation of mock objects using aspects. This isn’t something I’ve had a chance to try out but I suspect it has some drawbacks and any implementation may prove complex. If you try it out let me know how you get on.</p>
<p>Apart from tight-coupling between objects there are other problems you’ll come across when introducing mock objects while retrofitting unit tests in Java code.  Static and final methods are the enemy of mock objects as are public properties, particularly with something like EasyMock.  Statics and finals can’t be overridden and the mock object will have no control over access to public properties. If there are a lot of these in the code to be tested then it can cause problems for your mock objects.</p>
<p>Sometimes though these problems are code-smells and deserve to be refactored as you go.  Public properties are the antithesis of encapsulation and direct access should be replaced with the use of getter and setter methods<sup>2</sup>.  Statics often indicate a laziness or poor understanding of object-oriented design while a lot of finals can often be a sign of <a href="http://fintanp.wordpress.com/2007/03/15/premature-optimization/" target="_blank">premature optimisation</a>.</p>
<p>You can get around some of these problems with a slight refactoring of the code under test.  Refactoring as you go is part of the basic approach to writing a unit test anyway but when you’re working on existing code you need to do it carefully, especially if you have a limited understanding of what the code is doing in the first place.  Your best bet is to write as much of the test as you can, refactor the code a little and write more of the test.  Run the test each time you change something to make sure that you’re at least keeping the result of your test consistent with the previous result.</p>
<p>Finally, mock objects are great but not if you have to mock a complex data model.  Remember that the purpose of a mock object is to model the behaviour of some external dependency without having it actually do anything.  If you find that you’re creating mock object after mock object to model a set of beans you’re heading in the wrong direction.  If a complex data model is required you’re better off having a test data model handy that can be dropped into the code under test, perhaps as the return value from a call to an object that is mocking the model’s container.  Again there might be a code smell here if an object is essentially a container for some data but has a method that performs some transformation or operation on that data.  There may be a case of divided responsibilities and a need to split the class in two.</p>
<p>In the next part of the series I’ll talk about how to react when, having broken your dependencies using mock objects, your new unit test looks hideously complex.</p>
<p>&#8211; Fintan</p>
<hr />1 &#8211; Why re-invent the wheel?<br />
2 &#8211; God help you if you’re opposed to DI on encapsulation grounds but are quite happy to expose class properties publicly.  You&#8217;ll deserve everything you get&#8230;</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/fintanp.wordpress.com/88/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/fintanp.wordpress.com/88/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fintanp.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fintanp.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fintanp.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fintanp.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fintanp.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fintanp.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fintanp.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fintanp.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fintanp.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fintanp.wordpress.com/88/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=88&subd=fintanp&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://fintanp.wordpress.com/2007/10/23/retrofitting-unit-tests-part-3-mock-object-hell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9fefd4a9c0730bf11295b7f5bc1f685d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fintanp</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/10/banged-up-spoiler.jpg" medium="image">
			<media:title type="html">Spoiler worth more than car</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_attribution_small.gif" medium="image">
			<media:title type="html">Attribution</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_sharealike_small.gif" medium="image">
			<media:title type="html">Share Alike</media:title>
		</media:content>
	</item>
		<item>
		<title>Retrofitting Unit Tests Part 2 &#8211; When A Unit Test Isn&#8217;t</title>
		<link>http://fintanp.wordpress.com/2007/10/19/retrofitting-unit-tests-part-2-when-a-unit-test-isnt/</link>
		<comments>http://fintanp.wordpress.com/2007/10/19/retrofitting-unit-tests-part-2-when-a-unit-test-isnt/#comments</comments>
		<pubDate>Fri, 19 Oct 2007 12:17:28 +0000</pubDate>
		<dc:creator>fintanp</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fintanp.wordpress.com/2007/10/19/retrofitting-unit-tests-part-2-when-a-unit-test-isnt/</guid>
		<description><![CDATA[




Picture by icathing
Some rights reserved.


One of the most common mistakes I’ve found, particularly with teams who haven’t had a good deal of experience of unit testing or TDD, is that if they do have unit tests they&#8217;re often really integration tests with fake mustaches.  A small, relatively self-contained piece of code needs a database [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=84&subd=fintanp&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><table class="image" align="left" width="180">
<tr>
<td><img width="180" src="http://fintanp.files.wordpress.com/2007/10/chick-magnet.jpg?w=180" alt="Spoiler Carpentry" style="border:medium none;" /></td>
</tr>
<tr>
<td class="caption"><font color="gray" size="-2">Picture by <a href="http://www.flickr.com/photos/icathing/" target="_blank">icathing</a><br />
<a href="http://creativecommons.org/licenses/by-sa/2.0/" target="_blank"><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_attribution_small.gif" alt="Attribution" align="middle" /><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_sharealike_small.gif" alt="Share Alike" align="middle" /></a><a href="http://creativecommons.org/licenses/by-sa/2.0/deed.en-us" target="_blank">Some rights reserved.</a></font></td>
</tr>
</table>
<p>One of the most common mistakes I’ve found, particularly with teams who haven’t had a good deal of experience of unit testing or TDD, is that if they do have unit tests they&#8217;re often really integration tests with fake mustaches.  A small, relatively self-contained piece of code needs a database with test data or a running ORB and server process otherwise the test &#8220;fails&#8221;.</p>
<p>The issue here is one of scope and the key word is “unit”.  Typically this is a single class but could even be a single method in a class. A unit test should only test a single unit of code and not any of its external dependencies. If you’re writing a test to see if a particular Java class aggregates some data correctly prior to writing it to a database then you shouldn’t need a database to find out if it works or not.  The test ends when the database is invoked with the correct (or incorrect!) data and the database is treated like a black box that just works.</p>
<p><span id="more-84"></span>The reasons for this are quite simple. If you are relying on a database and the test fails you’ll have no idea if it failed because of some problem in the code or in the database.  You should be able to work this out, perhaps with a little digging, but false positives like this waste time and seriously reduce your confidence in the ability of unit tests to perform decent regression testing.  Imagine having a test that ran in the past but now fails after you make a change to the code being tested.  You have to figure out did it fail because of something you did or because the external dependency (e.g. the database) is broken or isn&#8217;t set up properly?</p>
<p>Another good reason is that your unit tests should run quickly. If it takes a long time to run all your tests as part of your build the inclination will be to avoid running them. Reducing the amount of execution time spent outside the code under test will help keep them quick. With Java projects I prefer to have the default Ant build target run my unit tests and have a separate &#8220;quick&#8221; build target to build without the tests. Apart from anything else it makes sure that I don&#8217;t forget to run my unit tests while I&#8217;m making changes and before I check any of those changes into source control.</p>
<p>Integration tests are important and if you have some masquerading as unit tests don’t bin them.  You can do one of two things:</p>
<ul>
<li>
Move them to a separate area and run them using a different test regime<sup>1</sup>.  Your unit tests have come out of the closet and are now proud integration tests.  Now go off and write unit tests to replace them, being careful to avoid dragging in the external dependencies.
</li>
<li>
Alternatively change the existing tests to decouple your external dependencies so that they don’t rely on them being in place to work. Drop the orb and the database and mock them.
</li>
</ul>
<p>Either way mock objects can be incredibly useful and I use them extensively in my tests. If you don’t know what mock objects are have a read of <a href="http://martinfowler.com/articles/mocksArentStubs.html">this great article by Martin Fowler</a> and some of the more meaty posts on <a href="http://www.mockobjects.org/">the Mock Objects blog</a>.  The basic idea is that you create a dummy version of the external component, set an expectation of how it should be used and behave but without it actually having to do any real work.</p>
<p>Treating external dependencies as black boxes like this is okay.  Imagine you have a class A which uses class B and you have a passing unit test for class B.  You can test class A with a mock class B and, if the test passes, can be highly confident that when you put A with a real B it&#8217;ll work.  On top of that your unit test for class A will run quicker and be less brittle.</p>
<p>In the next part of this series I&#8217;ll talk a bit more about mock objects and the problems with introducing them when retrofitting unit tests.</p>
<p>&#8211; Fintan</p>
<hr />1 &#8211; There is a school of thought that Continuous Integration should be a continuous run of your integration tests but that’s a whole different argument to be had.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/fintanp.wordpress.com/84/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/fintanp.wordpress.com/84/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fintanp.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fintanp.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fintanp.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fintanp.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fintanp.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fintanp.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fintanp.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fintanp.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fintanp.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fintanp.wordpress.com/84/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=84&subd=fintanp&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://fintanp.wordpress.com/2007/10/19/retrofitting-unit-tests-part-2-when-a-unit-test-isnt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9fefd4a9c0730bf11295b7f5bc1f685d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fintanp</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/10/chick-magnet.jpg" medium="image">
			<media:title type="html">Spoiler Carpentry</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_attribution_small.gif" medium="image">
			<media:title type="html">Attribution</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_sharealike_small.gif" medium="image">
			<media:title type="html">Share Alike</media:title>
		</media:content>
	</item>
		<item>
		<title>Retrofitting Unit Tests</title>
		<link>http://fintanp.wordpress.com/2007/10/18/retrofitting-unit-tests/</link>
		<comments>http://fintanp.wordpress.com/2007/10/18/retrofitting-unit-tests/#comments</comments>
		<pubDate>Thu, 18 Oct 2007 22:16:05 +0000</pubDate>
		<dc:creator>fintanp</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fintanp.wordpress.com/2007/10/18/retrofitting-unit-tests/</guid>
		<description><![CDATA[




Picture by hugovk
Some rights reserved.


A while ago I promised to write a few articles on the art of test-driven development or TDD1. Rather than starting with TDD itself I wanted to start by talking about what happens when you try to write unit tests after you write your code.
This can happen for any number of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=72&subd=fintanp&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><table class="image" align="left" width="180">
<tr>
<td><img width="180" src="http://fintanp.files.wordpress.com/2007/10/speedy-red-car-cropped.jpg?w=180" alt="Speedy Red Car" style="border:medium none;" /></td>
</tr>
<tr>
<td class="caption"><font color="gray" size="-2">Picture by <a href="http://www.flickr.com/photos/hugovk/" target="_blank">hugovk</a><br />
<a href="http://creativecommons.org/licenses/by-sa/2.0/" target="_blank"><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_attribution_small.gif" alt="Attribution" align="middle" /><img src="http://fintanp.files.wordpress.com/2007/04/cc_icon_sharealike_small.gif" alt="Share Alike" align="middle" /></a><a href="http://creativecommons.org/licenses/by-sa/2.0/deed.en-us" target="_blank">Some rights reserved.</a></font></td>
</tr>
</table>
<p>A while ago I promised to write a few articles on the art of test-driven development or <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a><sup>1</sup>. Rather than starting with TDD itself I wanted to start by talking about what happens when you try to write unit tests <em>after</em> you write your code.</p>
<p>This can happen for any number of reasons. A team may want a suite of unit tests with good coverage but may not be willing or experienced enough to either try TDD or make it work. All too frequently a team that isn&#8217;t used to writing unit tests, or can&#8217;t get it&#8217;s collective head around how you can write a test for something that doesn&#8217;t exist yet, will usually revert to writing the test afterwards. The result is that unit tests drop down on the priority list and are the first thing to be cut when a project starts slipping.</p>
<p><span id="more-72"></span>This isn’t helped by the fact that the very word “test” implies something done after the fact<sup>2</sup>. I’ve lost track of the number of interviews or conversations I’ve had where, when TDD comes up, I get a knowing look and the question “Did you really write your tests first?” as if it was okay, I was with friends and could admit that I just dive straight in and write the code first. No, I like to write my unit tests first. That’s why it’s called test-<em>driven</em> development.</p>
<p>As I’ve moved around in a couple of different jobs recently though I&#8217;ve found myself working on code with few<sup>3</sup> unit tests. As a result I’ve picked up a lot of experience in retrofitting unit-tests to existing code. Over the next few weeks I&#8217;ll be sharing some of the experiences I&#8217;ve had and how I solved some of the problems that came up.</p>
<p>First up: when a unit test isn&#8217;t.</p>
<p>&#8211; Fintan</p>
<hr />1 &#8211; And then proceeded to write nothing at all for the next few months&#8230;<br />
2 &#8211; Behaviour-Driven Development aims to fix this but more about that in a later article.<br />
3 &#8211; If any.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/fintanp.wordpress.com/72/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/fintanp.wordpress.com/72/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fintanp.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fintanp.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fintanp.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fintanp.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fintanp.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fintanp.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fintanp.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fintanp.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fintanp.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fintanp.wordpress.com/72/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=72&subd=fintanp&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://fintanp.wordpress.com/2007/10/18/retrofitting-unit-tests/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9fefd4a9c0730bf11295b7f5bc1f685d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fintanp</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/10/speedy-red-car-cropped.jpg" medium="image">
			<media:title type="html">Speedy Red Car</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_attribution_small.gif" medium="image">
			<media:title type="html">Attribution</media:title>
		</media:content>

		<media:content url="http://fintanp.files.wordpress.com/2007/04/cc_icon_sharealike_small.gif" medium="image">
			<media:title type="html">Share Alike</media:title>
		</media:content>
	</item>
	</channel>
</rss>