<?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>Jakub Korab &#187; testing</title>
	<atom:link href="http://www.jakubkorab.net/category/technology/testing/feed" rel="self" type="application/rss+xml" />
	<link>http://www.jakubkorab.net</link>
	<description>Tech, Opinion, and Doing Stuff</description>
	<lastBuildDate>Fri, 23 Jul 2010 16:27:19 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>A Better Builder</title>
		<link>http://www.jakubkorab.net/2009/10/a-better-builder.html</link>
		<comments>http://www.jakubkorab.net/2009/10/a-better-builder.html#comments</comments>
		<pubDate>Tue, 13 Oct 2009 22:12:24 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.jakubkorab.net/?p=226</guid>
		<description><![CDATA[The builder pattern should be familiar to anyone who has needed to change data from one format to another. Often called assemblers, translators or similar, they&#8217;re found peppered throughout almost every project. The idea is pretty simple:


public class HouseBuilder {
    public House buildHouse(OtherHouseType otherHouse) {
        [...]]]></description>
			<content:encoded><![CDATA[<p>The builder pattern should be familiar to anyone who has needed to change data from one format to another. Often called assemblers, translators or similar, they&#8217;re found peppered throughout almost every project. The idea is pretty simple:
</p>
<p>
<pre class="brush: java;">public class HouseBuilder {
    public House buildHouse(OtherHouseType otherHouse) {
        House house = new House();
        // copy a whole bunch of properties from the otherHouse....
        for (OtherWallType otherWall : otherHouse.getWalls()) {
            house.addWall(buildWall(otherWall));
        }
        return house;
    }

    private Wall buildWall(OtherWallType otherWall) {
        Wall wall = new Wall();
        // copy another whole bunch of other properties....
        // do something fancy every third Tuesday of the month...
        for (OtherWindowType otherWindow : otherWall.getWindows()) {
            wall.addWindow(buildWindow(otherWindow));
        }
        return wall;
    }

    private Window buildWindow(OtherWindowType otherWindow) {
        Window window = new Window();
        // you get the idea....
        return window;
    }
}</pre>
</p>
<p> It&#8217;s OK for translating small object graphs, but for non-trivial work, these things can turn into huge heaving masses of code. Because they&#8217;re pretty quick to knock out, they&#8217;re generally untested as the above code doesn&#8217;t really lend itself to it. Take the buildWall() method above &#8211; you can&#8217;t really exercise the &#8220;every third Tuesday&#8221; case easily without running through buildHouse(), and then calling buildWindow(). It becomes a pain to construct the data model to pump into test cases, and as we know, anything that&#8217;s not easy or highly visible doesn&#8217;t get tested. Did I just say that? Oops. Sorry, industry secret.
</p>
<p>
One strategy that&#8217;s applied is to write builders for each object type, i.e. HouseBuilder, WallBuilder, WindowBuilder. These are then either wired together via dependency injection (ugly as it exposes internal mechanics), or hard-coded in with a setter to substitute a dependency at test time. There&#8217;s also the drawback of a morass of tiny classes proliferating in a package somewhere. Not necessarily a bad thing, but when doing this sort of work there&#8217;s typically a good amount of refactoring, as well as use of utility classes to enrich data when moving between formats. Personally, not a big fan of this approach.</p>
<p>So, here&#8217;s a cool little trick:</p>
<p>
<pre class="brush: java;">public class MuchImprovedHouseBuilder {
    private MuchImprovedHouseBuilder delegate;

    public MuchImprovedHouseBuilder() {
        delegate = this;
    }

    void substituteInternalBuilder(MuchImprovedHouseBuilder otherBuilder) {
        delegate = otherBuilder;
    }

    public House buildHouse(OtherHouseType otherHouse) {
        House house = new House();
        // copy a whole bunch of properties from the otherHouse....
        for (OtherWallType otherWall : otherHouse.getWalls()) {
            house.addWall(delegate.buildWall(otherWall));
        }
        return house;
    }

    Wall buildWall(OtherWallType otherWall) {
        Wall wall = new Wall();
        // copy another whole bunch of other properties....
        // do something fancy every third Tuesday of the month...
        for (OtherWindowType otherWindow : otherWall.getWindows()) {
            wall.addWindow(delegate.buildWindow(otherWindow));
        }
        return wall;
    }

    Window buildWindow(OtherWindowType otherWindow) {
        Window window = new Window();
        // you get the idea....
        return window;
    }
}</pre>
</p>
<p>All of the translation is done in one builder class. On construction, a private field defines a &#8220;delegate&#8221;. Think of it as a placeholder that will do the &#8220;other bits&#8221; of the translation and set it to &#8220;this&#8221;. A package scoped setter allows a test to overwrite the builder with a mock. So with a bit of reference fiddling, we can then test one method at a time, without having to worry about the implementation details of the other methods in the class. All of the non-public methods are given package scope, so they can be tested straight out of your favourite test framework. So, you can now do this in live code:</p>
<p>
<pre class="brush: java;">
HouseBuilder builder = new HouseBuilder();
House house = builder.build(otherHouseType);
</pre>
</p>
<p>And at the same time write tests like this:</p>
<p>
<pre class="brush: java;">
HouseBuilder builder = new HouseBuilder();
HouseBuilder mockBuilder = EasyMock.createMock(HouseBuilder.class); // the classextension version of EasyMock
EasyMock.expect(mockBuilder.buildWindow(isA(OtherWindowType.class)).andReturn(new Window());
EasyMock.replay(mockBuilder);
builder.substituteInternalBuilder(mockBuilder);
Wall wall = builder.buildWall(otherWallType);
</pre>
</p>
<p>Simple, and you don&#8217;t have to stick in any new tools to achieve it.</p>
<p><img src="http://www.jakubkorab.net/wp-content/uploads/2009/10/bob_the_builder-231x300.jpg" alt="Bob&#039;s girlfriend misunderstood when he said his diet needed more iron." title="Bob&#039;s girlfriend misunderstood when he said his diet needed more iron." width="231" height="300" class="alignnone size-medium wp-image-238" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakubkorab.net/2009/10/a-better-builder.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Testing the Untestable</title>
		<link>http://www.jakubkorab.net/2009/07/testing-the-untestable.html</link>
		<comments>http://www.jakubkorab.net/2009/07/testing-the-untestable.html#comments</comments>
		<pubDate>Tue, 28 Jul 2009 22:25:12 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.jakubkorab.net/?p=193</guid>
		<description><![CDATA[Once upon a time you got sick of writing code and having it fail when you ran, or someone else did, and you learned to unit test your code.
You read the JUnit docs, and wrote tests for those classes which contained discrete, self-contained code. And quickly realised that the world doesn&#8217;t work like that. 
Code [...]]]></description>
			<content:encoded><![CDATA[<p>Once upon a time you got sick of writing code and having it fail when you ran, or someone else did, and you learned to unit test your code.</p>
<p>You read the JUnit docs, and wrote tests for those classes which contained discrete, self-contained code. And quickly realised that the world doesn&#8217;t work like that. </p>
<p>Code relies on other code. Often very complex code. And you discovered dependency injection. You abstracted out the collaborating class, and injected it in to the code. Great! </p>
<p>Now you could use stubs &#8211; code which always behaves in a certain way &#8211; as part of your test, and discretely use them to test the top level code. Awesome! For about two weeks.</p>
<p>The stubs became too inflexible, and every time you changed the interface of the class being stubbed, you had to change the stub too. Not only that, having the stubbed code behave the same way every time was too inflexible. What if you need to test how the top-level code reacts when its collaborators throw errors? </p>
<p>So you looked on the net and you learned about mock objects. It was like getting into a hot bath. Now you could dynamically define the behaviour of collaborating classes in every test. You could test exception handling! Excellent! Until once again, it wasn&#8217;t. </p>
<p>Because the world doesn&#8217;t work like that. Your code style develops. You want to use other patterns, and behaviours, that don&#8217;t fit well with the idea of injection, and which are a code-level implementation detail. Sometimes you just want to instantiate a class and use it. And not have to test it along with the code that uses it. Maybe it&#8217;s builders. Maybe it&#8217;s a stream that you want to write to. Conversely, you don&#8217;t want to litter your Spring config with objects of a tiny ganularity just for the purposes of testing. And you find that your testing tools aren&#8217;t enough. Not only that, they are now driving the design of your code.</p>
<p>What if you could write code at the level of abstraction that makes sense to you? Static helper methods? Builders? Package private classes that get instantiated from inside your code? What if you want to wire the objects in your application at a granularity that makes sense? </p>
<p>&#8220;Surely, you must be smoking!&#8221; I hear you say. &#8220;That is a pipe dream reserved for dynamic language programmers, not us grunting around at the coalface in Java.&#8221; Well, actually, no. The latest generation of unit testing tools allow you to do just that! With Java!</p>
<p>JMockit is one of the latest toolkits in the evolutionary chain of mocking tools. It depends on the instrumentation APIs in Java 6 to enable behaviour that was previously unattainable. One of the prerequisites is that you are using the latest 1.6 JDK for your code, but if you are &#8211; rock and roll. Let me demonstrate:</p>
<p>Let&#8217;s say that you are writing an application that blatantly violates the trademarks of MTV&#8217;s favourite show and tricks out rubbish cars. Here&#8217;s your main code:</p>
<pre class="brush: java;">
package demo;

public class PimpingService {

    private CarDao carDao;

    public void setCarDao(CarDao tradeDao) {
        this.carDao = tradeDao;
    }

    /**
     * Loads a car and pimps it, saving it and returning.
     * representative of a lot of code out in the wild.
     *
     * @param carId The primary key of the car to load.
     * @return The pimped ride.
     */
    public Car pimpRide(Long carId) {
        Car unpimpedCar = carDao.findCar(carId);
        Car pimpedCar = PaintShop.resprayWithFlames(unpimpedCar);

        if (pimpedCar.getValue() &gt; 100000) {
            ElectronicsWizard wizard = new ElectronicsWizard(24);
            pimpedCar = wizard.makeFullySick(pimpedCar);
        }

        try {
            carDao.save(pimpedCar);
        } catch (IllegalStateException isx) {
            // roll back our changes
            pimpedCar = unpimpedCar;
        }
        return pimpedCar;
    }
}
</pre>
<p>You&#8217;ve got some pretty interesting usage patterns here:</p>
<ul>
<li>a dependency injected DAO</li>
<li>use of static methods</li>
<li>object instantiation</li>
</ul>
<p>The first is pretty straightforward to mock up, but the others, not so much.</p>
<p>Let&#8217;s take a look at the other classes:</p>
<pre class="brush: java;">
package demo;

public final class Car {
    private final Double value;

    public Car(Double value) {
        this.value = value;
    }

    public Double getValue() {
        return value;
    }
}
</pre>
<pre class="brush: java;">
package demo;

public class CarDao {

    /**
     * Finds a car by its primary key.
     * @param carId The primary key.
     * @return A car if found, or null.
     */
    public Car findCar(Long carId) {
        // normally there'd  be some kind of jdbc thing here
        return new Car(100000d);
    }

    /**
     * Saves a car.
     * @param car The car.
     */
    public void save(Car car) {
        // ...
    }
}
</pre>
<pre class="brush: java;">
package demo;

public class PaintShop {

    /**
     * Resprays a car, increasing its value.
     * @param car The car.
     * @return A resprayed version of the car.
     */
    public final static Car resprayWithFlames(Car car) {
        Car resprayedCar = new Car(car.getValue() * 2);
        return resprayedCar;
    }

}
</pre>
<pre class="brush: java;">
package demo;

public class ElectronicsWizard {

    private int multiplier;

    public ElectronicsWizard(int multiplier) {
        this.multiplier = multiplier;
    }

    /**
     * Makes a car fully sick.
     * @param car The car to make fully sick.
     * @return A fully sick car.
     */
    public Car makeFullySick(Car car) {
        return new Car(car.getValue() * multiplier);
    }

}
</pre>
<p>So, as we run the code, things happen. We first load the car, and then we keep changing its value depending on what operations we run on it.</p>
<p>Let&#8217;s exercise it using JUnit and JMockit. This code uses JUnit 4 and JMockit 0.98.</p>
<pre class="brush: java;">
package demo;

import mockit.Expectations;
import mockit.Mocked;
import mockit.integration.junit4.JMockit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertSame;

@RunWith(JMockit.class)
public class TradeServiceTest {

    @Mocked
    private CarDao mockCarDao;
    @Mocked
    private ElectronicsWizard mockWizard;
    @Mocked
    private final PaintShop unusedMockPaintShop = null;
    private PimpingService pimpingService;

    @Before
    public void setUp() {
        pimpingService = new PimpingService();
        pimpingService.setCarDao(mockCarDao);
    }

    /**
     * Checks that happy path to pimping cars.
     */
    @Test
    public void testPimpRide() {
        final Long carId = 1L; // this is the id that we'll look up
        // the ride we'll expect to get back from the process
        final Car fullySickCar = new Car(300000.0);

        new Expectations() {
            { // static block

                // set an expectation on this mock that it will be invoked with
                // a car id
                mockCarDao.findCar(withEqual(carId));
                Car foundCar = new Car(100000.0);
                returns(foundCar); // return value from last mock call

                // this static method will be called next
                PaintShop.resprayWithFlames(withSameInstance(foundCar));
                Car resprayedCar = new Car(200000.0);
                returns(resprayedCar); // set its return value

                new ElectronicsWizard(24);
                returns(mockWizard);

                mockWizard.makeFullySick(withSameInstance(resprayedCar));
                returns(fullySickCar);

                // we're done
                mockCarDao.save(withSameInstance(fullySickCar));
            }
        };

        // all that's left is to invoke our service and see what happens
        Car resprayedCar = pimpingService.pimpRide(carId);
        assertSame(fullySickCar, resprayedCar);
    }

}
</pre>
<p>So what&#8217;s going on here?</p>
<ul>
<li>We import a few JMockit classes (line 11) to help us with the testing. Because of the way that JMockit operates, there are bits and pieces that are required to integrate the toolkit with the testing framework being used. Here, we import the JUnit version.</li>
<li>You need to create placeholders (lines 14-19) for each of the classes that you will be mocking, regardless of whether you want to instantiate them, such as in the case of our unusedMockPaintShop, on which we will just be calling static methods.</li>
<li>You define mock objects behaviour in an Expectations block. This makes use of a syntax similar to JMock, where all your code is defined in a static block (line 38). If you are used to EasyMock, you&#8217;ll immediately notice the change in style. You use static methods of the Expectations class immediately after the expected method calls to define how the mock object will behave. Line 44&#8217;s returns(foundCar) is an instruction for the mockCarDao used on line 42. </li>
</ul>
<p>The rest pretty much looks like a standard unit test. What about some different behaviour from the instantiated class?</p>
<pre class="brush: java;">
    /**
     * Checks that the electronics wizard won't get called in if the paintshop gives us a
     * car with a small value amount.
     */
    @Test
    public void testPimpRideElectronicsWizardNotCalled() {
        final Long carId = 1L;
        // the car we'll expect to get back - look at the new value
        final Car resprayedCar = new Car(50000.0);

        new Expectations() {
            {
                mockCarDao.findCar(withEqual(carId));
                Car foundCar = new Car(100000.0);
                returns(foundCar);

                PaintShop.resprayWithFlames(withSameInstance(foundCar));
                returns(resprayedCar);

                // its return value is &lt; 100,000 so no wizard here
                // if the wizard was invoked, you'd get an error:
                // Unexpected invocation of: demo.ElectronicsWizard#ElectronicsWizard(int)
                // it's @Mocked, remember?

                mockCarDao.save(withSameInstance(resprayedCar));
            }
        };

        Car tradeReturnedFromService = pimpingService.pimpRide(carId);
        assertSame(resprayedCar, tradeReturnedFromService);
    }
</pre>
<p>That&#8217;s all well and good. But what about testing how our code will handle exceptions?</p>
<pre class="brush: java;">
    /**
     * Checks that no wizard work will be done if respraying gives us a
     * car with a small value amount.
     */
    @Test
    public void testPimpRideElectronicsWizardNotCalledSavingBreaks() {
        final Long carId = 1L;
        final Car foundCar = new Car(100000.0);

        new Expectations() {
            {
                mockCarDao.findCar(withEqual(carId));
                returns(foundCar);

                PaintShop.resprayWithFlames(withSameInstance(foundCar));
                Car resprayedCar = new Car(50000.0);
                returns(resprayedCar);

                mockCarDao.save(withSameInstance(resprayedCar));
                // dao throws a humorous antipodean complaint here
                IllegalStateException isx = new IllegalStateException(&quot;Ooh bugger&quot;);
                throwsException(isx);
            }
        };

        Car tradeReturnedFromService = pimpingService.pimpRide(carId);
        // the service should have just returned the car it found
        assertSame(foundCar, tradeReturnedFromService);
    }
</pre>
<p>That&#8217;s nowhere near what you can do with JMockit, but it should give you a good taster. Code that was previously untestable, can now be dealt with as easily as a straightforward class with injected dependencies. Go forth and code in whatever way makes sense to you, DI or not, content in the knowledge that it&#8217;s all good and testable.</p>
<img alt="Man, am I happy I can test my code." src="http://www.buddytv.com/articles/pimp-my-ride/images/mad-mike-1.jpg" title="Mad Mike" width="200" height="150" />
]]></content:encoded>
			<wfw:commentRss>http://www.jakubkorab.net/2009/07/testing-the-untestable.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Unit Testing the Database Tier</title>
		<link>http://www.jakubkorab.net/2008/01/unit-testing-the-database-tier.html</link>
		<comments>http://www.jakubkorab.net/2008/01/unit-testing-the-database-tier.html#comments</comments>
		<pubDate>Fri, 25 Jan 2008 10:14:38 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[architecture]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://www.jakubkorab.net/2008/01/unit-testing-the-database-tier.html</guid>
		<description><![CDATA[var dzone_url="http://www.jakubkorab.net/2008/01/unit-testing-the-database-tier.html"; var dzone_title = "Unit Testing the Database Tier"; var dzone_blurb = "Why unit testing database dependent code is so problematic, and suggestions as to how to enable it both technically and socially."; var dzone_style = "1";Unit testing database code is a bit of a funny problem. Most developers can pretty easily get their [...]]]></description>
			<content:encoded><![CDATA[<p><script type="text/javascript">var dzone_url="http://www.jakubkorab.net/2008/01/unit-testing-the-database-tier.html"; var dzone_title = "Unit Testing the Database Tier"; var dzone_blurb = "Why unit testing database dependent code is so problematic, and suggestions as to how to enable it both technically and socially."; var dzone_style = "1";</script><script src="http://widgets.dzone.com/widgets/zoneit.js" language="javascript"></script>Unit testing database code is a bit of a funny problem. Most developers can pretty easily get their heads around unit testing a piece of Java code using interfaces and mock objects. When it comes to database code or DAOs, it suddenly becomes particularly difficult. But why, what is so difficult about testing stuff against the database? Surprisingly enough, the answer is that it has nothing to do with coding or a particular framework, although these do play their parts. It comes down to a complex web of human interaction, version control and managing environments. Let me explain.</p>
<p>The standard unit test has three basic phases:</p>
<ul>
<li>Setup (@Before)</li>
<li>Test (@Test)</li>
<li>Tear down (@After)</li>
</ul>
<p>The first sets the test environment into an expected state, the second runs the test and checks that the outcome is as expected, while the final one clears up any test resources.</p>
<p>How does this relate to database testing? Let&#8217;s say that we have a DAO that performs a particular select statement. Our test should be to retrieve a particular number of records from a known set. Easy enough. The precondition of course, is that you have a known set to begin with.</p>
<p>It&#8217;s ALL about the environment.</p>
<p>Most large development projects go like this: The database guys update the schema. The developers write the code. The developers need a particular data set to exercise the various use cases so they add it to the schema. It all becomes a bit messy.</p>
<p>Eventually, very complex data sets are set up by everyone concerned in a primary schema that keeps getting updated. The database schema generally is not version controlled, as it is constantly being redefined using DDL statements run by the DBAs. Most of the time you will be lucky to get a backup of a schema, with all of the data truncated, as the schema and supporting code (i.e. the application) moves between environments.</p>
<p>Getting back to the test. You set up your data by hand in the master schema so that there were three items in the widgets table where some condition was true. You write your test, it runs against the schema, pulls out the expected three widgets and everything is great. You check in the tests. A week later your colleague, Bob, adds another widget to satisfy his test condition. Your test all of a sudden returns 4 items and the test breaks.</p>
<p>Of course, Bob didn&#8217;t actually run your test because he was too busy with his own and the test suite isn&#8217;t clean anyway because everyone is falling over each other.</p>
<p>Sound familiar?</p>
<p>What about inserts? The precondition: no sprockets were in the table, the test: insert a sprocket, the postcondition: a sprocket is in your table. Kind of hard to test under the above conditions isn&#8217;t it? For one thing, the exact data of the test sprocket may be in the table, so checking by value may give you false positives, while deleting it may get rid of more records than you wanted. What about concurrent tests? With a group of developers running the same tests, they start tripping over each other very quickly and the whole effort becomes an exercise in frustration. At this point the development manager throws up his hands, says that this automated testing thing is a load of bollocks and to get back to your work because they didn&#8217;t deal with all this when he was doing VB. Somewhere else, Kent Beck sheds a tear&#8230;</p>
<p>Let&#8217;s examine what goes on in Ruby on Rails. One of the best ideas that was popularized by this framework was its method for database unit testing. A developer&#8217;s workspace has multiple environments by default &#8211; development, test and production. You develop against the development schema, designing table structures, and playing with the user interface to your heart&#8217;s content. When you run unit tests, the following happens &#8211; the schema from development is copied into the test database with no data in it. The framework imports version controlled sets of test data (saved as YAML files) into this new schema. Whenever a test is run, it is guaranteed that the database will be in this state. Any changes a test makes are visible only within the scope of this one test. The tear down step cleans out your changes. This makes life so much simpler, especially if you have been working in the nightmare scenario above.</p>
<p>So how do we get the same sort of effect in a corporate development environment?</p>
<p><em>You need multiple database schemas in order to unit test your db code.</em></p>
<p>Pause and re-read that line. It&#8217;s not negotiable. Probably two per developer. One with sample data to use while you work on the user interface. The other, a temporary one for unit testing. A whole development team using the one schema does not work. Most projects do it, but that doesn&#8217;t mean that it&#8217;s a good idea.</p>
<p>Some suggestions for how to manage this. The DBAs have their own schemas. The full DDL for the database is kept in version control. After each change, the full database DDL is dumped and checked in. No UPDATE TABLE statements. Ever. This way you are guaranteed that if you ever want to get a baseline of your system, you can also rebuild the database as it existed at this time. I worked on a very large telecoms project with a huge development team, and this worked. Well.</p>
<p>The test data for your environments is stored in version control &#8211; at the very least, as dumps of insert statements. For unit testing purposes, a dedicated unit test framework is beneficial. DBUnit performs the same task in Java as described above for Rails &#8211; it loads test data from dumps (a number of formats are supported), and guarantees that the test database exists in the expected state when each test is run.</p>
<p>To test your database code, refresh your test schema with the one from version control &#8211; typically using your chosen build system. Ant tasks are generally pretty good for this. Now run your test cases. Gorgeous! No tripping over other people, and your tests are guaranteed to work the same each time. No excuses for a red bar.</p>
<p>So why is unit testing databases so difficult if it doesn&#8217;t have to be? Most of the time it involves process change and getting out of bad habits, not just a tool. And change means convincing people. Generally, managers do not understand what benefit there is in multiple database schemas, as it is seen to increase complexity and therefore risk, and DBAs like to have full control over what is going on on their servers. The topic of databases and processes is also a great one for religious zeal.</p>
<p>The process outlined above should explain the hows and whys to the individuals involved. The changes above mean a little bit more setup initially, but a saner development process.</p>
<p>A nice side effect is how easy upgrading databases through your environments can become. Run the latest DDL against a fresh schema, get the differences between it and your target environment using a database compare tool, and fire it off. Beautiful.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakubkorab.net/2008/01/unit-testing-the-database-tier.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How crap is your code?</title>
		<link>http://www.jakubkorab.net/2007/12/how-crap-is-your-code.html</link>
		<comments>http://www.jakubkorab.net/2007/12/how-crap-is-your-code.html#comments</comments>
		<pubDate>Tue, 18 Dec 2007 19:50:00 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.jakubkorab.net/2007/12/how-crap-is-your-code</guid>
		<description><![CDATA[Now you can find out with Crap4J. Can wait to run some projects through it. I&#8217;m curious as to what the code quality looks like on some of the larger Open Source projects (Dom4J looks pretty good though).
I love stats. I don&#8217;t know what it is. They&#8217;re like horoscopes, or something. Pinch of salt and [...]]]></description>
			<content:encoded><![CDATA[<p>Now you can find out with <a href="http://www.crap4j.org/">Crap4J</a>. Can wait to run some projects through it. I&#8217;m curious as to what the code quality looks like on some of the larger Open Source projects (Dom4J looks pretty good though).</p>
<p>I love stats. I don&#8217;t know what it is. They&#8217;re like horoscopes, or something. Pinch of salt and all that, but you can&#8217;t not read them. Even better with diagrams <img src='http://www.jakubkorab.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakubkorab.net/2007/12/how-crap-is-your-code.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit testing made simpler(!)</title>
		<link>http://www.jakubkorab.net/2007/12/unit-testing-made-simpler.html</link>
		<comments>http://www.jakubkorab.net/2007/12/unit-testing-made-simpler.html#comments</comments>
		<pubDate>Tue, 18 Dec 2007 19:30:00 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.jakubkorab.net/2007/12/unit-testing-made-simpler</guid>
		<description><![CDATA[What is simpler than writing a JUnit test? Getting someone else to write them for you! The really nice people at Agitar Software have developed a couple of tools as part of their &#8220;No Java Class Left Behind&#8221; programme, that will write JUnit tests for your existing code to prove that it works as expected. [...]]]></description>
			<content:encoded><![CDATA[<p>What is simpler than writing a JUnit test? Getting someone else to write them for you! The really nice people at <a href="http://www.agitar.com/">Agitar Software</a> have developed a couple of tools as part of their &#8220;No Java Class Left Behind&#8221; programme, that will write JUnit tests for your existing code to prove that it works as expected. This sort of testing is known as characterization testing, and is useful if someone gives you a big steamy pile of untested code that you have to make sure won&#8217;t break when you start refactoring it (I have a great story about that, but you need to buy me a beer first).</p>
<p>They have a commercial product called AgitarOne that is worth checking out, which runs on your intranet and you can do a whole bunch of stuff in, but they also have a free version called <a href="http://www.junitfactory.com/">JUnit Factory</a>. You can either upload your code to them via your browser or via an Eclipse plugin. Code In, Tests Out! Superb!</p>
<p>It&#8217;s not a substitute for development time testing, but still a great tool for your professional arsenal. How cool will you look when you put a test suite around that nonsense you have been given to work against <img src='http://www.jakubkorab.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>There&#8217;s a <a href="http://blog.businessofsoftware.org/2007/09/alberto-savoia-.html">great interview with Alberto Savoia</a> from Agitar on the Business of Software conference site that goes into the how&#8217;s and why&#8217;s.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakubkorab.net/2007/12/unit-testing-made-simpler.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to test the middle tier of a Spring application</title>
		<link>http://www.jakubkorab.net/2007/08/how-to-test-the-middle-tier-of-a-spring-application.html</link>
		<comments>http://www.jakubkorab.net/2007/08/how-to-test-the-middle-tier-of-a-spring-application.html#comments</comments>
		<pubDate>Mon, 13 Aug 2007 14:20:00 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://www.jakubkorab.net/2007/08/how-to-test-the-middle-tier-of-a-spring-application</guid>
		<description><![CDATA[Since the advent of dependency injection (DI) as a staple of enterprise development using tools such as Spring or Guice, your code has become a lot easier to test. You no longer need to code up voodoo such as plugging in dummy resource locators or the like based on some random environment variable to tell [...]]]></description>
			<content:encoded><![CDATA[<p>Since the advent of dependency injection (DI) as a staple of enterprise development using tools such as Spring or Guice, your code has become a lot easier to test. You no longer need to code up voodoo such as plugging in dummy resource locators or the like based on some random environment variable to tell your code to switch into &#8220;test mode&#8221;. Everything is a POJO with interfaces as dependencies rather than classes, which means that it can be easily tested as a POJO. Nevertheless, it still surprises me as to how many people don&#8217;t know how to do this. Perhaps it is the perception that you need to have a running back end to test a service tier, or that you need the rest of the system to test a web front end. Not so. </p>
<p>Enter the mock object. According to <a href="http://en.wikipedia.org/wiki/Mock_Object">Wikipedia</a> &#8211; &#8220;mock objects are simulated objects that mimic the behavior of real objects in controlled ways&#8221;. And thanks to freely available Java toolkits such as <a href="http://www.easymock.org/">EasyMock</a> and <a href="http://www.jmock.org/">jMock</a>, making them available to your tests is as easy as plugin in a Jar file into your IDE. I&#8217;m a heavy user of EasyMock, so what follows is a simplified example of a jUnit test testing the middle tier of your typical DI-based application.</p>
<p>The following example deals with the following classes:</p>
<ul>
<li>WorkItem &#8211; a simple value object</li>
<li>WorkItemException &#8211; an exception</li>
<li>WorkItemService &#8211; an interface of a middle tier class</li>
<li>WorkItemDao &#8211; an interface to the data layer of our application. <i>This is what we are going to mock up.</i></li>
<li>WorkItemServiceImpl &#8211; an implementation of that class. <i>This is what we are going to test.</i></li>
<li>WorkItemServiceImplTest &#8211; our test class</li>
</ul>
<p>First, let&#8217;s get the uninteresting classes out of the way. Our WorkItem is just a bean that gets passed between the layers:</p>
<pre class="brush: java;">package jkorab.example.mock;

public class WorkItem {
 int workItemNo;

 public int getWorkItemNo() {
    return workItemNo;
 }

 public void setWorkItemNo(int workItemNo) {
   this.workItemNo = workItemNo;
 }
}
</pre>
<p>The WorkItemException is an exception that gets thrown:</p>
<pre class="brush: java;">package jkorab.example.mock;

public class WorkItemException extends Exception {
  private static final long serialVersionUID = 1L;
}
</pre>
<p>Now we come to the class that normally sits in the business tier of our application:</p>
<pre class="brush: java;">package jkorab.example.mock;

public interface WorkItemService {

  /**
   * Trivial method. Given a workItem number &gt; 0, returns a workItem instance.
   * Used to show how you might test the wrapping of an exception.
   *
   * @return WorkItem or null.
   */
  public abstract WorkItem generateWorkItem(int workItemNo);

}
</pre>
<p>Let&#8217;s take a look at the interface of the class it uses to do its work:</p>
<pre class="brush: java;">package jkorab.example.mock;

public interface WorkItemDao {

  /**
   * Given a workItem number &gt; 0, returns a workItem instance.
   * @param workItemNo workItem number
   * @return WorkItem if workItemNo &gt; 0.
   * @throws WorkItemException if workItemNo &lt;= 0.
   */
  public WorkItem getWorkItem(int workItemNo) throws WorkItemException;

}
</pre>
<p>Our example is, as is the spirit of most tutorials, pretty contrived. The top tier of our application wants to load a WorkItem, so it passes a work item number to the service tier. The service tier gets the work item, and if it cannot find it, returns null. The DAO on the other hand, gets a work item number and it the number is less than or equal to 0, it throws an exception, otherwise it loads the WorkItem.</p>
<p>Here&#8217;s the implementation of the WorkItemService:</p>
<pre class="brush: java;">package jkorab.example.mock;

public class WorkItemServiceImpl implements WorkItemService {
  private WorkItemDao workItemDao;

  public void setWorkItemDao(WorkItemDao workItemDao) {
    this.workItemDao = workItemDao;
  }

  /* (non-Javadoc)
   * @see jkorab.example.mock.WorkItemService#generateWorkItem(int)
   */
  public WorkItem generateWorkItem(int workItemNo) {
    WorkItem workItem = null;
    try {
      workItem = workItemDao.getWorkItem(workItemNo);
    } catch (WorkItemException workItemException) {
      // log and continue. we'll return null.
    }
    return workItem;
  }
}
</pre>
<p>The class here is doing what the interface &#8220;said on the tin&#8221;. In addition it has a setter so that the DI container can supply it with a DAO implementation. That&#8217;s where our hook is that will enable us to test the service without an actual DAO implementation.</p>
<p>The first thing we need in order to write a test class is a mock DAO. This is the component that the service class will call. In addition we will also need a mock control. Think of this as a component that instructs your DAO as to how it should behave &#8211; kind of like a way of programming your Tivo/Set top box/VCR (for those who still have one <img src='http://www.jakubkorab.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).</p>
<pre class="brush: java;">MockControl control = MockControl.createControl(WorkItemDao.class);
WorkItemDao mockDao = (WorkItemDao) control.getMock();

WorkItemServiceImpl service = new WorkItemServiceImpl();
service.setWorkItemDao(mockDao);
</pre>
<p>The MockControl class is used to get an instance appropriate to the interface we are mocking up. From this, calling getMock() will return to us an implementation of our DAO interface which we then set on the instance of the class we are testing. This would normally be done in the setUp() method of your jUnit test class, so that each of your tests is guaranteed to get a mock instance in a fresh state, which you can then play with.</p>
<p>In our test method, we can then get on with doing some work. First, we tell our DAO exactly how we would like it to behave:</p>
<pre class="brush: java;">// set the methods that you expect to be called
mockDao.getWorkItem(1);

// set the return value
WorkItem returnedWorkItem = new WorkItem();
returnedWorkItem.setWorkItemNo(1);
control.setReturnValue(returnedWorkItem);

// reset the control object to play back our script
control.replay();
</pre>
<p>The last line tells the mock control object that the mock DAO is now in a state where the test can be run on it.</p>
<pre class="brush: java;">WorkItem workItem = service.generateWorkItem(1);
assertNotNull(workItem);
assertEquals(1, workItem.getWorkItemNo());

// verify that the methods we expected to be called on the mock object
// were actually called
control.verify();
</pre>
<p>The last line tells the control object to check itself to ensure that all the methods that we told it would be called were in fact called. It will throw an  Exception if they weren&#8217;t causing our test to fail.</p>
<p>The behaviour described above can be used to test the behaviours of your service class under <b><i>any</i></b> circumstances. We can mock up the throwing of an Exception, unexpected behaviours, whatever we want. Here&#8217;s the full test class:</p>
<pre class="brush: java;">package jkorab.example.mock;

import jkorab.example.mock.WorkItem;
import jkorab.example.mock.WorkItemDao;
import jkorab.example.mock.WorkItemException;
import jkorab.example.mock.WorkItemServiceImpl;

import org.easymock.MockControl;

import junit.framework.TestCase;

public class WorkItemServiceImplTest extends TestCase {
  private MockControl control;
  private WorkItemDao mockDao;
  private WorkItemServiceImpl service;

  public void setUp() {
    control = MockControl.createControl(WorkItemDao.class);
    mockDao = (WorkItemDao) control.getMock();

    service = new WorkItemServiceImpl();
    service.setWorkItemDao(mockDao);
  }

  /**
   * Checks that a WorkItem will be returned if the class receives a workItem
   * number greater than 0.
   *
   * @throws WorkItemException
   */
  public void testGenerateWorkItem() throws WorkItemException {
    // set the methods that you expect to be called
    mockDao.getWorkItem(1);
    // set the return value
    WorkItem returnedWorkItem = new WorkItem();
    returnedWorkItem.setWorkItemNo(1);
    control.setReturnValue(returnedWorkItem);
    // reset the control object to play back our script
    control.replay();

    WorkItem workItem = service.generateWorkItem(1);
    assertNotNull(workItem);
    assertEquals(1, workItem.getWorkItemNo());

    // verify that the methods we expected to be called on the mock object
    // were actually called
    control.verify();
  }

  /**
   * Checks that a null will be returned if the class receives a workItem
   * number equal to 0 rather than throwing an exception.
   * @throws WorkItemException
   */
  public void testGenerateWorkItemNullValue() throws WorkItemException {
    // set the methods that you expect to be called
    mockDao.getWorkItem(0);
    // set the control to throw an exception
    control.setThrowable(new WorkItemException());
    control.replay();

    WorkItem workItem = service.generateWorkItem(0);
    assertNull(workItem);
  }
}
</pre>
<p>This is a great way to test, not only because of its simplicity, but also it being future proof. Let&#8217;s examine another way of writing the same tests without using mock objects:</p>
<pre class="brush: java;">
WorkItemDao mockDao = new MockDao() {
  public WorkItem getWorkItem(int workItemNo) throws WorkItemException;
    WorkItem returnedWorkItem = new WorkItem();
    returnedWorkItem.setWorkItemNo(1);
  }
};

WorkItemServiceImpl service = new WorkItemServiceImpl();
service.setWorkItemDao(mockDao);

WorkItem workItem = service.generateWorkItem(1);
assertNotNull(workItem);
assertEquals(1, workItem.getWorkItemNo());
</pre>
<p>At first glance, coding up an anonymous class looks like less work, but consider the following:</p>
<ul>
<li>if your class is more complex than this (and to be honest, most are) then you will end up with potentially dozens of anonymous implementations.</li>
<li>if the DAO has more than one method, you will end up with a lot of code that does nothing.</li>
<li>if the interface on your DAO changes then you will end up with a lot of tests that won&#8217;t compile, because your classes no longer match the interface.</li>
</ul>
<p>This just isn&#8217;t the case with mock objects. Mock objects are created at runtime, and you only have to define the behaviours that you are interested in. The technique can also be used to test existing code &#8211; refactor your dependencies to an interface, use DI or a constructor if this isn&#8217;t an option, and voila, a testable class. 100% code coverage, and future-proof. No more excuses.</p>
<p>If you are interested in more info on mock objects check out the <a href="http://www.mockobjects.com/">MockObjects</a> blog.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakubkorab.net/2007/08/how-to-test-the-middle-tier-of-a-spring-application.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
