<?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>Jayway Team Blog &#187; tdd</title>
	<atom:link href="http://blog.jayway.com/tag/tdd/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using RenamingDelegatingContext to mock ContentResolver in Android</title>
		<link>http://blog.jayway.com/2011/10/10/using-renamingdelegatingcontext-to-mock-contentresolver-in-android/</link>
		<comments>http://blog.jayway.com/2011/10/10/using-renamingdelegatingcontext-to-mock-contentresolver-in-android/#comments</comments>
		<pubDate>Mon, 10 Oct 2011 21:40:57 +0000</pubDate>
		<dc:creator>Tomas Nilsson</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10207</guid>
		<description><![CDATA[Mocking Context Testing in Android can be complex, especially when your component is not isolated from the Android framework. One example of this is when your component is performing file system tasks using Context. E.g, the Activity class has the following methods (inherited from Context): openOrCreateDatabase(); deleteDatabase(); getDatabasePath(); openFileInput(); openFileOutput(); getFileStreamPath(); deleteFile(); getCacheDir(); When calling [...]]]></description>
			<content:encoded><![CDATA[<h3>Mocking Context</h3>
<p>Testing in Android can be complex, especially when your component is not isolated from the Android framework. One example of this is when your component is performing file system tasks using <a title="Context" href="http://developer.android.com/reference/android/content/Context.html">Context</a>. E.g, the <a title="Activity" href="http://developer.android.com/reference/android/app/Activity.html">Activity</a> class has the following methods (inherited from <a title="Context" href="http://developer.android.com/reference/android/content/Context.html">Context</a>):</p>
<pre>openOrCreateDatabase();
deleteDatabase();
getDatabasePath();
openFileInput();
openFileOutput();
getFileStreamPath();
deleteFile();
getCacheDir();</pre>
<p>When calling any of the methods above, <a title="Context" href="http://developer.android.com/reference/android/content/Context.html">Context</a> directs the calls to parts of the file system dedicated to your specific application, usually located under <code>/data/data/&lt;your.applications.package.name&gt;/</code>. To mock away these type of operations, there is a component called <a title="RenamingDelegatingContext" href="http://developer.android.com/reference/android/test/RenamingDelegatingContext.html">RenamingDelegatingContext</a>. It basically allows you to replace the context used when calling file system methods, re-directing the call to a mocked data file instead of the real file. The source code for <a title="RenamingDelegatingContext" href="http://developer.android.com/reference/android/test/RenamingDelegatingContext.html">RenamingDelegatingContext</a> can be looked at here:</p>
<p><a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.5_r1/android/test/RenamingDelegatingContext.java">RenamingDelegatingContext</a></p>
<p>There are a number of tutorials on how to use RenamingDelegatingContext to mock away your files or databases;</p>
<ul>
<li><a href="http://dtmilano.blogspot.com/2009/11/android-testing-mock-contexts.html">http://dtmilano.blogspot.com/2009/11/android-testing-mock-contexts.html</a></li>
<li><a href="http://www.devdaily.com/java/jwarehouse/android/test-runner/src/android/test/ProviderTestCase.java.shtml">http://www.devdaily.com/java/jwarehouse/android/test-runner/src/android/test/ProviderTestCase.java.shtml</a></li>
</ul>
<h3>Advanced use of RenamingDelegatingContext</h3>
<p>In addition to open resources directly using <a title="Context" href="http://developer.android.com/reference/android/content/Context.html">Context</a>, one common task is to open a resoure using a <a title="ContentResolver" href="http://developer.android.com/guide/topics/providers/content-providers.html#basics">ContentResolver</a>:</p>
<pre>Uri uri = Uri.parse("content://authority/path");
InputStream is = getContext().getContentResolver().openInputStream(uri);</pre>
<p>The <code>getContext()</code> call can be omitted if you're making the call from within an Activity or Service, where the component itself is a <a title="Context" href="http://developer.android.com/reference/android/content/Context.html">Context</a>.</p>
<p>One might want the returned InputStream to point to a test resource instead of the real resource. This can be achieved with some research. When opening the InputStream, the ContentResolver finds the proper provider for the given authority (see <a title="ContentProvider" href="http://developer.android.com/guide/topics/providers/content-providers.html">ContentProvider</a> section for more detail). The source code reveals more on how this is done:</p>
<p><a title="ContentResolver.OpenInputStream" href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.5_r1/android/content/ContentResolver.java#ContentResolver.openInputStream%28android.net.Uri%29">ContentResolver.openInputStream</a></p>
<pre>public final InputStream openInputStream(Uri uri) throws FileNotFoundException {
   ...
   } else {
       AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r");
       try {
           return fd != null ? fd.createInputStream() : null;
       } catch (IOException e) {
           throw new FileNotFoundException("Unable to create stream");
       }
   }
}</pre>
<p><a title="ContentResolver.OpenAssetFileDescriptor" href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.5_r1/android/content/ContentResolver.java#ContentResolver.openAssetFileDescriptor%28android.net.Uri%2Cjava.lang.String%29">ContentResolver.openAssetFileDescriptor</a></p>
<pre>public final AssetFileDescriptor openAssetFileDescriptor(Uri uri, String mode) throws FileNotFoundException {
    ...
    } else {
        IContentProvider provider = acquireProvider(uri);
        ...
        try {
            AssetFileDescriptor fd = provider.openAssetFile(uri, mode);
            ...
            ParcelFileDescriptor pfd = new ParcelFileDescriptorInner(fd.getParcelFileDescriptor(), provider);
            return new AssetFileDescriptor(pfd, fd.getStartOffset(), fd.getDeclaredLength());
        } catch ( ...</pre>
<p>As seen in the extracts above, the ContentResolver acquires the correct provider based on the given <code>Uri</code> (authority). In order for us to mock away this behavior, we need to do four things:</p>
<ol>
<li>Use a RenamingDelegatingContext to mock away the real Context (target Context) in the test.</li>
<li>Override the <code>getContentResolver</code> in RenamingDelegatingContext to return a <a title="MockContentResolver" href="http://developer.android.com/reference/android/test/mock/MockContentResolver.html">MockContentResolver</a>.</li>
<li>Create a ContentProvider to return a AssetFileDescriptor pointing to the test resource.</li>
<li>Register the ContentProvider with the MockContentResolver to handle the authority we want to override.</li>
</ol>
<h3>Mocking ContentResolver</h3>
<pre>public class MockContentResolverTestCase extends AssetManagerAndroidTestCase {

    public static final String URI_PREFIX = "content://";
    public static final String URI_AUTHORITY = "com.my.authority";
    public static final String URI_PATH = "/additional_path/";
    public static final String URI_FULL = URI_PREFIX + URI_AUTHORITY + URI_PATH;

    private RenamingSystemSettingsContext mockContext;
    private LinkedList assetFileQueue;

    public void createMockContext(Context targetContext) {
        mockContext = new RenamingSystemSettingsContext(targetContext);
        assetFileQueue = new LinkedList();
    }

    public Context getMockContext() {
        return mockContext;
    }

    public void pushAssetFile(String fileName) {
        assetFileQueue.offer(fileName);
    }

    public class RenamingSystemSettingsContext extends RenamingDelegatingContext {

        private static final String PREFIX = "test.";   // Not actually used, but needed by RenamingDelegatingContext

        public RenamingSystemSettingsContext(Context targetContext) {
            super(targetContext, PREFIX);
            super.makeExistingFilesAndDbsAccessible();
        }

        @Override
        public ContentResolver getContentResolver() {
            MockContentProvider provider = new MockContentProvider() {
                AssetFileDescriptor ret = null;

                @Override
                public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
                    try {
                        ret = openTestResourceAsAssetFileDescriptor(assetFileQueue.poll());
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new FileNotFoundException();
                    }
                    return ret;
                }
            };
            MockContentResolver resolver = new MockContentResolver();
            resolver.addProvider(URI_AUTHORITY, provider);
            return resolver;
        }
    }
}</pre>
<h3>AssetManagerAndroidTestCase</h3>
<pre>public class AssetManagerAndroidTestCase extends AndroidTestCase {
    /*
      * For unknown reason, the 'getTestContext' method is hidden in source. Use
      * reflection to access it.
      */
    private AssetManager getAssetManagerForTestContext() throws Exception {
        Method m = AndroidTestCase.class.getMethod("getTestContext",
                new Class[]{});
        mContext = (Context) m.invoke(this, (Object[]) null);
        return mContext.getAssets();
    }
    protected InputStream openTestResourceAsStream(String fileName) throws Exception {
        AssetManager testAssets = getAssetManagerForTestContext();
        return testAssets.open(fileName, AssetManager.ACCESS_STREAMING);
    }

    protected AssetFileDescriptor openTestResourceAsAssetFileDescriptor(String fileName) throws Exception {
        AssetManager testAsset = getAssetManagerForTestContext();
        return testAsset.openFd(fileName);
    }
}</pre>
<h3>Creating an example test</h3>
<p>In the following example, the <em>test_file.midi</em> is a text file stored in the <code>res/asset/</code> directory. The <em>.midi</em> extension is a workaround to prevent the Android Asset Packaging Tool (aapt) from compressing the file. If the file is compressed, it can only be opened as an InputStream and not as a FileDescriptor, which is needed for mocking away the ContentProvider. See <a href="https://code.google.com/p/android/issues/detail?id=3122">this bug</a> for more info.</p>
<pre>public class ExampleTests extends MockContentResolverTestCase {

    public void testUseCustomSettingsFile() throws IOException {
        String assetFile = "test_file.midi";
        createMockContext(getContext());
        pushAssetFile(assetFile);
        Uri uri = Uri.parse(URI_FULL);

        InputStream is = getMockContext().getContentResolver().openInputStream(uri);

        assertEquals("Text in test file", getStringFromStream(is));
    }

    public static String getStringFromStream(InputStream is) throws IOException {
        int size = is.available();
        byte[] buf = new byte[size];
        is.read(buf);
        return new String(buf);
    }
}
</pre>
<p>That's it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/10/using-renamingdelegatingcontext-to-mock-contentresolver-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automated Testing is Like Optimizing</title>
		<link>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/</link>
		<comments>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 09:57:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6982</guid>
		<description><![CDATA[I have my roots in the Atari demo scene, so I know the joys of optimizing the inner-loop of a software texture mapper down to the last assembly instruction. The bragging rights of knowing that not a single clock cycle is wasted. I am also grown up enough to know that this is not a [...]]]></description>
			<content:encoded><![CDATA[<p>I have my roots in the Atari demo scene, so I know the joys of optimizing the inner-loop of a software texture mapper down to the last assembly instruction. The bragging rights of knowing that not a single clock cycle is wasted. I am also grown up enough to know that this is not a skill many needs to practice. In fact going about in this way on a customers project would be fraudulent, even if I could dazzle them with how cool optimizing for branch predictions is.</p>
<p>I can understand the joys of making sure that every potential bug is removed, and the bragging rights of 100% automated test coverage as well. But I would argue that it is equally fraudulent to claim 100% automated test coverage to a client as a virtue. I am not arguing that automated tests should be abandoned, far from it. I am arguing that automated tests should be applied with the same care as optimizations. </p>
<h2>Premature Automated Testing is Bad</h2>
<p>We have all learned that premature optimizations are bad. Guessing what could fail is hard, the only safe route would be to write a check for everything! There is even a coding practice encouraging this, test driven development or TDD for short. Which should really be called ADD for assertion driven development. Since what is done is not testing, but checking by asserting conditions against a specification.</p>
<p>Take a moment and answer honestly; for any project with good automated test coverage what is the ratio between time spent writing the checks versus the time these checks have saved you? In my experience the more zealously automated test coverage is applied, the more time is spent maintaining the tests. For any project where automated tests have been written first, and code later, I have yet never experienced that the checks have saved more time than the time they cost to develop and maintain.</p>
<p>When optimizing it is hard to find the bottlenecks. Gut feeling is good many times, but often even your gut feeling is wrong and the performance bottle neck is somewhere you would never expect. It is the same with defects in code, your gut feeling is good for pin-pointing many defects, but often the cause is something you never expected. So instead of wasting time guessing what the problems may be down the road you should inspect and measure where the issues are. And when an issue is found then you write a check for it to ensure it does not break again.</p>
<h2>Change the Algorithm</h2>
<p>The best optimization is often not to optimize at all, but to change to a better algorithm. Writing a bubble sort algorithm in assembly will never yield a better result than a sloppy merge sort written in C anyway, so do not waste your time.</p>
<p>Same can be said about code quality. If you have many issues, and your code breaks often, adding automated tests will only be bandaid until it breaks the next time. Change the code into something more stable. If needed, write checks to ensure the new implementation conforms to the same public API when you refactor it. Take notice to write checks with as good coverage as needed when you are about to refactor your code not before.</p>
<p>If you architect your application with many small independent units, each with a clearly defined public API, then refactoring is not a big problem.</p>
<h2>Perceived Quality</h2>
<p>All green lights and a 100% automated test coverage looks good on a report. But it can never catch what is most important of all; is the application valuable to the user? In that regard the 100% automated test coverage is a false safety, it gives the illusion of quality. A dangerous illusion that can be used to blind managers, customers and other stakeholders from seeing the real issues with the application.</p>
<p>There is yet no testing framework made that is as efficient as a human being actually using the application. Not just people blindly following a test protocol, that is even worse. But stake holders using the application as intended. Not just short burst before committing code to source control, but also regularly on longer sessions. So that you get a feel for how the app is used, what works, or just what grinds your gears. Usability issues are also issues and should be dealt with.</p>
<p>Not every issue is created equal. With the limited time every project have fixing, or predicting, each and every one of them is never feasible. So do not waste time fixing the one in a million issue, or writing checks for the bread and butter code. But do make sure the application fails gracefully. Fail as gracefully as you can for the end-user, they are very forgiving if you fail with style and make sure no data is lost. But also fail gracefully for yourself, be generous with logging when you do fail. And remember to add an automated check so that the reason for the failure may never raise again, once you fixed it.</p>
<h2>Model View Controller</h2>
<p>All application logic can be divided into three categories. Model for the business logic of your product, View for the display and input to and from the user (or other application), and Controller that is the mediator between the two. Any application of any significant size will have smaller MVC patterns within their units as well. Well defined boundaries between what is a Model, View and Controller is not only good for re-usability, maintainability, and replacing parts. It is also great for testing. Have well defined and testable public APIs for the parts, and the private implementations tend to be simpler and of higher quality. Do not let the public API be defined by how something is implemented, let the implementation be defined by how you want to access it from the outside. </p>
<p>Writing unit tests for the Model of your application is seldom a waste of time. Often the Model is what you begin implementing, so using unit tests as the incubator until you have enough logic in place to implement the first draft of your application is only rational; code that is unused is seldom of any quality at all.</p>
<p>Writing unit tests for the View yield much less returns on investment. It is also highly probably that you will have to write these tests over and over again. I would go so far as call them harmful, too many automated tests on the Views may in fact discourage you from doing drastic but needed usability changes. And no automated test in the world can ever flag if a View is usable, looks good, and feels right to the end-user.</p>
<p>Writing unit tests for the Controller should be a waste of time, otherwise your Controller is doing too much. A Controller should only be the mediator between the View and Model, if it does more then it should be split up and the proper parts moved into Model and View layers. So writing unit tests for a good Controller is basically just verifying that your are using the APIs of the Model and Views correctly. </p>
<h2>Conclusions</h2>
<p>We have learned that premature optimization is bad, often counter productive or wastes our time for minimal gains. Let us all grow up and also learn that premature automated testing is equally bad. The time we have is to precious to waste on overzealous automated testing instead of adding real value to the product by applying tests where it makes real difference to the products quality.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Test Driven Development in XCode</title>
		<link>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/</link>
		<comments>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 08:35:26 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4301</guid>
		<description><![CDATA[Test Driven Development, or TDD for short, is a simple software development practice where unit tests, small focused test cases, drive the development forward. This is most easily explained by the Three Rules of TDD that dictate the following: You are not allowed to write any production code unless it is to make a failing [...]]]></description>
			<content:encoded><![CDATA[<p>
        <a href="http://en.wikipedia.org/wiki/Test-driven_development" title="Test-driven development - Wikipedia, the free encyclopedia">Test Driven Development</a>, or TDD for short, is a simple software development practice where unit tests, small focused test cases, drive the development forward. This is most easily explained by the <a href="http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd" title="TheThreeRulesOfTdd">Three Rules of TDD</a> that dictate the following:</p>
<ol>
<li>You are not allowed to write any production code unless it is to make a failing unit test pass.</li>
<li>You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.</li>
<li>You are not allowed to write any more production code than is sufficient to pass the one failing unit test.</li>
</ol>
<p>That means that test cases are written before any production code. Not all tests are written up front, it's rather that a small test is written, then a small piece of production code is written that only allows that test to pass. This is repeated in <a href="http://www.agiledata.org/essays/tdd.html">many small iterations</a>: test, fail, code, pass, test, fail, code, pass...<br/><br />
Many people consider TDD to encourage clean code, simple architectures and a stable system that's actually testable. Plus, it's also fun! We've <a href="/tag/tdd/">previously written</a> about various aspects of TDD, but in this tutorial we'll focus on how it works for XCode projects, where you write apps for Mac and iPhone. We will create a simple XCode project, do some special configuration steps and then demonstrate how TDD can be used to write your app. We're going to use <a href="http://www.sente.ch/software/ocunit/">OCUnit</a> and its framework SenTestingKit, which nowadays is included with Apple's XCode tools.
</p>
<h2>Creating the Calculator project</h2>
<p>
Let's start by creating a new project in XCode. You can pick any template, since we aren't going to touch the generated code. I picked a Window-based iPhone project. Name the project <em>Calculator</em>. Select New Target from the Project menu. Under Cocoa select Unit test Bundle. Call it <em>UnitTests</em> (I've had problems with space in the target name so avoid that) and add it to the project. We now need to change some small settings for this target. Select the UnitTests target and hit Command-I for Info. Select the Build tab and locate <em>Other Linker Flags</em>. Replace <em>Cocoa</em> with <em>Foundation</em>. Also remove the entry for <em>GCC_PREFIX_HEADER</em>.
</p>
<p>
Now it's time to create your test suite. Create a new group in your project and call it "Test Classes". Add a new File to this group and make sure it's a Cocoa->Objective-C test case class. Name it <em>CalculatorTest.m</em>. Uncheck "Also create CalculatorTest.h" since we don't need a header file. Don't add it to the Calculator target, but check it to be included in UnitTests. Open CalculatorTest.m file and above the @implementation declaration add:</p>
<pre class="brush:objc">#import &lt;SenTestingKit/SenTestingKit.h&gt;
#import "Calculator.h"
@interface CalculatorTest : SenTestCase
{

}
@end</pre>
<p>This is just because we don't want a rather empty header file. All your test classes will look like this.</p>
<p>Following TDD, we should build right away.  First make sure that the active target is "UnitTets" and then press the "Build" button. This will not only do a normal build, but also perform some shell script magic and actually execute the  unit tests. Now the build fails of course, since Calculator.h can't be found.</p>
<p>So let's add a file which represents production code. Create a new empty Cocoa Touch Objective-C class called Calculator.m (also create the .h file), this is the class that we want to test. Don't forget to check that they should be included in both your targets. Notice that we mix Cocoa and Cocoa Touch, that's is fine - all code is executed on your Mac. Build again, and this time you'll see in the build log that everything built and the test suite was executed, but contained 0 test cases. Let's remedy that.
</p>
<h2>Writing test cases</h2>
<p>
Next we want to write our first test case. Open up CalculatorTest.m and add the following method:</p>
<pre class="brush:objc">-(void)testAdd
{
        Calculator* calculator = [[Calculator alloc] init];
        int result = [calculator add:5 to:6];
}</pre>
<p>All methods that start with "test" will be recognized as being a test case, and automatically run when building the target. Try and build and you'll unsurprisingly get the erro "unrecognized selector sent to instance...". That's all good. Let's add the add method to our Calculator class. In Calculator.h add:</p>
<pre class="brush:objc">-(int)add:(int)a to:(int)b;</pre>
<p>Then in Calculator.m add:</p>
<pre class="brush:objc">-(int)add:(int)a to:(int)b
{
        return 0;
}</pre>
<p>That should be enough to let it compile and run, right? Try it out! You'll see that it indeed build and executes the tests.
</p>
<p>
        Now we change the test so that it actually checks that we get the expected value back. We want to "assert" that the returned value is what we expected. Change the test case to look like this:</p>
<pre class="brush:objc">-(void)testAdd
{
        Calculator* calculator = [[Calculator alloc] init];
        int expected = 11;
        int result = [calculator add:5 to:6];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}</pre>
<p>Build and you see that the test runs and fails since our calculator always returns 0 regardless of the input. Change the production code so that it returns a+b and rerun the test. Nice, we have a successful build and our test works! Notice the fast cycle of test, code, fix, rerun. The point of TDD is to write tests and production code in small iterations so that you always have something stable (= the tests pass). If you follow the rules of TDD you'll have a growing amount of test cases and you'll right away know when something breaks.
</p>
<p>
Let's write one more test. Now we want to add the functionality to allow one number to be divided by another. Start up like before with a new test case like this:</p>
<pre class="brush:objc">-(void)testDivide
{
        Calculator* calculator = [[Calculator alloc] init];
        float expected = 2.5;
        int result = [calculator divide:5 by:2];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}</pre>
<p>You see, this time we expect to get back a float. Add the corresponding divide method to Calculator.h and Calculator.m. If you need help see the full code listing at the end of this article. You might notice that just returning a/b gives you 2.0. Type cast the return value to (float)a/b and you'll be fine. Go ahead when you got it working.
</p>
<p>
What happens if you try to divide something with zero? Well, why not add a test case for this scenario? If you're into maths you know that the result of this operation is undefined. How do you expect something to be undefined? This is tricky. <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  Start off by just expecting any number and see what you get back. As you see, the float value "inf" is returned. It seems like Objective-C treats the zero as "a value approaching zero" and that will indeed result in infinity in a division. But, hey, that might not be what we want our calculator to do. Let's change the test case to expect an exception to be raised instead:</p>
<pre class="brush:objc">-(void)testDivideByZero
{
        Calculator* calculator = [[Calculator alloc] init];
        STAssertThrows([calculator divide:5 by:0],
                @"We expected an exception to be raised when dividing by 0");
}</pre>
<p>Build and notice the error message when no exception was raised. Now change the production code to something like this:</p>
<pre class="brush:objc">-(float)divide:(int)a by:(int)b
{
        float result =  (float)a/b;
        if (result==INFINITY) {
                [NSException raise:@"Cannot divide by zero!"
                            format:@"Not possible to divide %d with %d", a,b];
        }
        return result;
}</pre>
<p>Rerun and smile as the test passes! There are many different variants of asserts you can do with SenTestingKit. Compare objects with STAssertEqualObjects. STAssertTrue to check that a returned boolean is true. Open up SentTestCase_Macros.h if you want to see what you can play around with. By the way. You might have tried using NSLog in your test cases (just to experiment). This is nothing you would do in real life, as you want all necessary information in the fail message and output nothing if the test passes. Anyway, since the tests are actually run using a separate shell script for the UnitTest target you won't see the log in your console as usual. Instead check the build log and click the "text" icon to the right for the "Run test suite" step.
</p>
<h2>Wrapping up</h2>
<p>
Finally, if you look at your test class you might notice that we're allocating a new Calculator for every test case, and we never release them. That's no good. Luckily there are setUp and tearDown methods that will be launched automatically before and after each test case. Change your implementation to look like this (this is the final listing):</p>
<pre class="brush:objc">#import &lt;SenTestingKit/SenTestingKit.h&gt;
#import "Calculator.h"
@interface CalculatorTest : SenTestCase
{
        Calculator* calculator;
}
@end

@implementation CalculatorTest

- (void) setUp
{
        calculator = [[Calculator alloc] init];
}

-(void)tearDown
{
        [calculator release];
}

-(void)testAdd
{
        int expected = 11;
        int result = [calculator add:5 to:6];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}

-(void)testDivide
{
        float expected = 2.5;
        float result = [calculator divide:5 by:2];
        STAssertEquals(expected, result,
                @"We expected %f, but it was %f",expected,result);
}

-(void)testDivideByZero
{
        STAssertThrows([calculator divide:5 by:0],
                @"We expected an exception to be raised when dividing by 0");
}
@end</pre>
</p>
<p>
For completeness, here's the listing for Calculator.h:</p>
<pre class="brush:objc">#import <Foundation/Foundation.h>

@interface Calculator : NSObject {

}

-(int)add:(int)a to:(int)b;
-(float)divide:(int)a by:(int)b;

@end</pre>
<p>and for Calculator.m:</p>
<pre class="brush:objc">#import "Calculator.h"

@implementation Calculator

-(int)add:(int)a to:(int)b
{
        return a+b;
}

-(float)divide:(int)a by:(int)b
{
        float result =  (float)a/b;
        if (result==INFINITY) {
                [NSException raise:@"Cannot divide by zero!"
                            format:@"Not possible to divide %d with %d", a,b];
        }
        return result;
}

@end</pre>
<p>Next blog post we'll see how to automate the running of test cases on a build server called Hudson!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Mocking static methods in Java system classes</title>
		<link>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/</link>
		<comments>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/#comments</comments>
		<pubDate>Sun, 17 May 2009 10:34:11 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1714</guid>
		<description><![CDATA[As you may already know PowerMock can be used to easily mock static methods which is normally not possible with standard mock frameworks such as EasyMock, JMock or Mockito. All you have to do is to use mockStatic in one of the PowerMock extension API's as well as telling PowerMock to enable the class for [...]]]></description>
			<content:encoded><![CDATA[<p>As you may already know <a href="http://www.powermock.org">PowerMock</a> can be used to easily mock static methods which is normally not possible with standard mock frameworks such as EasyMock, JMock or Mockito. All you have to do is to use <code>mockStatic</code> in one of the PowerMock extension API's as well as telling PowerMock to enable the class for testing using the @PrepareForTest annotation. A simple example of this can be seen below (using the EasyMock extension API):</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Greeter <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> getGreeting<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> name<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #ff0000;">&quot;Greetings &quot;</span> + string;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>And the test:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>PowerMockRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span> Greeter.<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MockStaticExampleTest <span style="color: #66cc66;">&#123;</span>
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockStaticExample<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> expectedGreeting = <span style="color: #ff0000;">&quot;greeting&quot;</span>;
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> nameToGreet = <span style="color: #ff0000;">&quot;name&quot;</span>;
&nbsp;
		mockStatic<span style="color: #66cc66;">&#40;</span>Greeter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
		expect<span style="color: #66cc66;">&#40;</span>Greeting.<span style="color: #006600;">getGreeting</span><span style="color: #66cc66;">&#40;</span>nameToGreet<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span>expectedGreeting<span style="color: #66cc66;">&#41;</span>;
		replayAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> actualGreeting = Greeter.<span style="color: #006600;">getGreeting</span><span style="color: #66cc66;">&#40;</span>nameToGreet<span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verifyAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Expected and actual greeting did not match&quot;</span>,
                                  expectedGreeting, actualGreeting<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The "power" behind PowerMock lies in its ability to modify the byte-code of the classes specified in the PrepareForTest annotation to make them testable. But because of restrictions enforced by the Java run-time PowerMock is simply not allowed to byte-code manipulate certain classes dynamically. These classes are those that are loaded by Java's bootstrap class-loader such as for example <code>java.net.URLEncoder</code>, <code>java.lang.System</code> and other "system classes" located in the java.lang or java.net package etc. While is this generally not a problem it may be so if you need to mock static methods in these classes because PowerMock cannot prepare them for test. So how do we get around this problem?</p>
<h3>How does PowerMock work?</h3>
<p>To start of with we probably should describe how PowerMock actually works under hood. What happens when PowerMock makes a class testable is that the byte-code is changed so that each method call, constructor call, field call etc are first routed to something that we refer to as the MockGateway. Simply put the MockGateway decides if it's OK for the call to be delegated to the original method/constructor/field or if a mock object should be returned instead. The MockGateway communicates with a MockRepository which stores all mock objects that has been setup for the current test method. Since PowerMock is just a layer on top of other mock frameworks we leave it for the underlying framework to do the actual mock creation, recording and verification of the mocks. The created mocks are put into the MockRepository by the PowerMock mock extension API. Basically all standard mock frameworks use CGLib to create a mock object which means that they're based on a hierarchical model (CGLib creates a sub class of the class to test at run-time which is the actual mock object) instead of a delegation model which PowerMock uses through it's byte-code manipulation by delegating to the MockGateway. This means that e.g. if a class is final CGLib cannot create a sub-class of it at run-time and therefore we can't mock it. So this is why most mock frameworks have the limitations that PowerMock doesn't.</p>
<h3>So how do we mock static methods in a system class?</h3>
<p>Since there's no way for PowerMock to modify the byte-code of a system class how do we route all calls to the MockGateway? The answer is quite simple, don't modify the system class itself but modify the class calling the system class! Thus outgoing calls to methods in the system class can be routed to the MockGateway instead of the system class intercepting incoming calls. That sounds simple enough but there's one more catch. As we saw earlier you set up expectations in the EasyMock extension API by reusing the standard expect method, e.g. </p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span>Greeting.<span style="color: #006600;">getGreeting</span><span style="color: #66cc66;">&#40;</span>nameToGreet<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span>expectedGreeting<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>and this usually works fine because <code>Greeting </code>has been prepared for test and the call to method <code>getGreeting</code> is routed to the MockGateway. But in cases of system classes a call to a static method is NOT intercepted by the system class itself as described above and thus the call is never routed to the MockGatway. The solution is to prepare the actual test class for test as well so that the outgoing method call to <code>getGreeting</code> in the expect method is routed to the MockGateway as well! So let's look at a very simple example to demonstrate how to mock a call to <code>URLEncoder.encode(..)</code>:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyEncoder
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> performEncode<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AUnsupportedEncodingException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">UnsupportedEncodingException</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AURLEncoder+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">URLEncoder</span></a>.<span style="color: #006600;">encode</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something&quot;</span>, <span style="color: #ff0000;">&quot;encoding&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and the test:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>PowerMockRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#123;</span> MyEncoder.<span style="color: #000000; font-weight: bold;">class</span>, MyEncoderTest.<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyEncoderTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> demoOfSystemClassMocking<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
		mockStatic<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AURLEncoder+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">URLEncoder</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		expect<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AURLEncoder+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">URLEncoder</span></a>.<span style="color: #006600;">encode</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something&quot;</span>, <span style="color: #ff0000;">&quot;encoding&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
                         .<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something else&quot;</span><span style="color: #66cc66;">&#41;</span>;
		replayAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something else&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> MyEncoder<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">performEncode</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verifyAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<h3>But wait, will this work for <em>final</em> system classes?</h3>
<p>That's a really good question because as we said earlier PowerMock delegates the mock creation process to the underlying mock framework (such as EasyMock) which uses CGLib. So even when mocking static methods the underlying mock framework is still used to create the CGLib mock of the class where the static methods are located. PowerMock then make use of the underlying framework's functionality to hold state for all recorded method invocations etc so that we don't have to deal with that in PowerMock as well. So usually what PowerMock does when it encounters a final class that should be prepared for test is simply to remove the final modifier. This means that CGLib can be used to create the mock object of this class without any problems. But what about a final system class? There's no way for PowerMock to remove the final modifier of a system class so what to do? What PowerMock does in these cases is to create a completely new class at run-time with the exact same structure as the original final system class. I.e. all method names and their corresponding signature are copied to a this new replica class. To allow for partial mocking all static methods of the replica class delegates to the original method in the final system class. It's also the replica class that is being mocked by the underlying mock framework instead of the original system class. The MockGateway then figures out that all methods bound for this particular system class should be routed to the replica mock instead. Thus mocking of static methods in final system classes such as <code>java.lang.System</code> or <code>java.lang.String</code> works as well. As a side note it would actually be possible to use this technique to implement duck-typing in Java as well. Anyway, here's an example to demonstrate what we've just said:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SystemPropertyMockDemo <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> getSystemProperty<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIOException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IOException</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">getProperty</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;property&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and the test:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>PowerMockRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#123;</span> SystemPropertyMockDemo.<span style="color: #000000; font-weight: bold;">class</span>, SystemPropertyMockDemoTest.<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SystemPropertyMockDemoTest
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> demoOfFinalSystemClassMocking<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
		mockStatic<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		expect<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">getProperty</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;property&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;my property&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		replayAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;my property&quot;</span>,
                                  <span style="color: #000000; font-weight: bold;">new</span> SystemPropertyMockDemo<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getSystemProperty</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verifyAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<h3>Conclusion</h3>
<p>As we've seen PowerMock is capable of achieving things not normally possible with standard mock frameworks because of technical limitations. Using PowerMock you can virtually choose any design you like without having to worry about the testability (or mockability to be more precise) aspects. Please visit our <a href="http://www.powermock.org">website</a> for more information and downloads.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Testing Among the Clouds, Part 2</title>
		<link>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/</link>
		<comments>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 14:22:56 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[typica]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=357</guid>
		<description><![CDATA[In a recent post I wrote about the particular problems we've been having with integration testing the Spring LDAP project and the use we've made of Amazon EC2 for solving these problems. In this post I'll present the implementation details. Prerequisites In order to keep this reasonably brief I'll have to refer to the getting [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a target="_blank" href="http://blog.jayway.com/2008/09/11/testing-among-the-clouds/">recent post</a> I wrote about the particular problems we've been having with integration testing the <a target="_blank" href="http://springframework.org/ldap">Spring LDAP</a> project and the use we've made of <a target="_blank" href="http://aws.amazon.com/ec2/">Amazon EC2</a> for solving these problems. In this post I'll present the implementation details.</p>
<h3>Prerequisites</h3>
<p>In order to keep this reasonably brief I'll have to refer to the <a target="_blank" href="http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/">getting started guide</a> for information on how to get going with Amazon EC2.</p>
<h3>A FactoryBean to Launch EC2 Instances</h3>
<p>What we want to achieve here is to launch an EC2 instance transparently and independently of the actual test code. Ideally, the test code should be oblivious of the target server and we want to externalize those details to external configuration. We will use Spring's excellent JUnit test support to automatically wire the integration test setup and make sure that the target server is up and running before the actual test code is running.</p>
<p>A powerful way to transparently perform complex initialization logic when using Spring is the <a target="_blank" href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-extension-factorybean"><code>FactoryBean</code></a> concept. We will create a <code>FactoryBean</code> implementation to launch the EC2 image and set up our target resource:</p>
<pre class="java">AbstractEc2InstanceLaunchingFactoryBean.<span style="color: #006600;">java</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> AbstractEc2InstanceLaunchingFactoryBean <span style="color: #000000; font-weight: bold;">extends</span> AbstractFactoryBean <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">int</span> INSTANCE_START_SLEEP_TIME = <span style="color: #cc66cc;">1000</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> DEFAULT_PREPARATION_SLEEP_TIME = <span style="color: #cc66cc;">30000</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Log log = LogFactory.<span style="color: #006600;">getLog</span><span style="color: #66cc66;">&#40;</span>AbstractEc2InstanceLaunchingFactoryBean.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> imageName;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsKey;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsSecretKey;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> keypairName;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> groupName;
  <span style="color: #000000; font-weight: bold;">private</span> Instance instance;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">long</span> preparationSleepTime = DEFAULT_PREPARATION_SLEEP_TIME;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setImageName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> imageName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">imageName</span> = imageName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setAwsKey<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsKey<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">awsKey</span> = awsKey;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setAwsSecretKey<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsSecretKey<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">awsSecretKey</span> = awsSecretKey;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setKeypairName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> keypairName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">keypairName</span> = keypairName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setGroupName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> groupName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">groupName</span> = groupName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setPreparationSleepTime<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">long</span> preparationSleepTime<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">preparationSleepTime</span> = preparationSleepTime;
  <span style="color: #66cc66;">&#125;</span>
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> createInstance<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>imageName, <span style="color: #ff0000;">&quot;ImageName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>awsKey, <span style="color: #ff0000;">&quot;AwsKey must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>awsSecretKey, <span style="color: #ff0000;">&quot;AwsSecretKey must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>keypairName, <span style="color: #ff0000;">&quot;KeyName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>groupName, <span style="color: #ff0000;">&quot;GroupName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
      log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Launching EC2 instance for image: &quot;</span> + imageName<span style="color: #66cc66;">&#41;</span>;
&nbsp;
      Jec2 jec2 = <span style="color: #000000; font-weight: bold;">new</span> Jec2<span style="color: #66cc66;">&#40;</span>awsKey, awsSecretKey<span style="color: #66cc66;">&#41;</span>;
      LaunchConfiguration launchConfiguration = <span style="color: #000000; font-weight: bold;">new</span> LaunchConfiguration<span style="color: #66cc66;">&#40;</span>imageName<span style="color: #66cc66;">&#41;</span>;
      launchConfiguration.<span style="color: #006600;">setKeyName</span><span style="color: #66cc66;">&#40;</span>keypairName<span style="color: #66cc66;">&#41;</span>;
      launchConfiguration.<span style="color: #006600;">setSecurityGroup</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span>groupName<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
      ReservationDescription reservationDescription = jec2.<span style="color: #006600;">runInstances</span><span style="color: #66cc66;">&#40;</span>launchConfiguration<span style="color: #66cc66;">&#41;</span>;
      instance = reservationDescription.<span style="color: #006600;">getInstances</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>!instance.<span style="color: #006600;">isRunning</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &amp;&amp; !instance.<span style="color: #006600;">isTerminated</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
          log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Instance still starting up; sleeping &quot;</span> + INSTANCE_START_SLEEP_TIME + <span style="color: #ff0000;">&quot;ms&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a>.<span style="color: #006600;">sleep</span><span style="color: #66cc66;">&#40;</span>INSTANCE_START_SLEEP_TIME<span style="color: #66cc66;">&#41;</span>;
          reservationDescription = jec2.<span style="color: #006600;">describeInstances</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">getInstanceId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
          instance = reservationDescription.<span style="color: #006600;">getInstances</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">isRunning</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
          log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;EC2 instance is now running&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>preparationSleepTime &gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
              log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Sleeping &quot;</span> + preparationSleepTime + <span style="color: #ff0000;">&quot;ms allowing instance services to start up properly.&quot;</span><span style="color: #66cc66;">&#41;</span>;
              <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a>.<span style="color: #006600;">sleep</span><span style="color: #66cc66;">&#40;</span>preparationSleepTime<span style="color: #66cc66;">&#41;</span>;
              log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Instance prepared - proceeding&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <span style="color: #66cc66;">&#125;</span>
          <span style="color: #000000; font-weight: bold;">return</span> doCreateInstance<span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">getDnsName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
          <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIllegalStateException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalStateException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Failed to start a new instance&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> doCreateInstance<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> ip<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a>;
&nbsp;
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> destroyInstance<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> ignored<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">instance</span> != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Shutting down instance&quot;</span><span style="color: #66cc66;">&#41;</span>;
      Jec2 jec2 = <span style="color: #000000; font-weight: bold;">new</span> Jec2<span style="color: #66cc66;">&#40;</span>awsKey, awsSecretKey<span style="color: #66cc66;">&#41;</span>;
      jec2.<span style="color: #006600;">terminateInstances</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">instance</span>.<span style="color: #006600;">getInstanceId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This superclass makes use of the <a target="_blank" href="http://code.google.com/p/typica/">typica</a> library (<a target="_blank" href="http://mvnrepository.com/artifact/com.google.code.typica/typica">also available in maven</a>) to launch the EC2 instance and delegates to <code>doCreateInstance</code> for creating the target resource that we will use in our test case. In our setup we want to create a <code>ContextSource</code>, which is the Spring LDAP equivalent of a <code>DataSource</code>:</p>
<pre class="java">ContextSourceEc2InstanceLaunchingFactoryBean.<span style="color: #006600;">java</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContextSourceEc2InstanceLaunchingFactoryBean <span style="color: #000000; font-weight: bold;">extends</span> AbstractEc2InstanceLaunchingFactoryBean <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> base;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> userDn;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password;
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">Class</span> getObjectType<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> ContextSource.<span style="color: #000000; font-weight: bold;">class</span>;
  <span style="color: #66cc66;">&#125;</span>
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> doCreateInstance<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> dnsName<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasText</span><span style="color: #66cc66;">&#40;</span>userDn<span style="color: #66cc66;">&#41;</span>;
    LdapContextSource instance = <span style="color: #000000; font-weight: bold;">new</span> LdapContextSource<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setUrl</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ldap://&quot;</span> + dnsName<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setUserDn</span><span style="color: #66cc66;">&#40;</span>userDn<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setPassword</span><span style="color: #66cc66;">&#40;</span>password<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setBase</span><span style="color: #66cc66;">&#40;</span>base<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    instance.<span style="color: #006600;">afterPropertiesSet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">return</span> instance;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setBase<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> base<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">base</span> = base;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setUserDn<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> userDn<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">userDn</span> = userDn;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setPassword<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">password</span> = password;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Note that the <code>AbstractEc2InstanceLaunchingFactoryBean</code> will wait for the instance to start up properly. It will also wait an additional period of time once the instance is up and running to allow for all relevant services to start up properly. Finally it will  automatically close down the launched instance once it is properly shut down (which it will be when executing using the Spring automated test support).</p>
<h3>Test Case Configuration</h3>
<p>We now have the infrastructure to have the EC2 instance launched transparently from a Spring Application Context. All we need to do is configure it:</p>
<pre class="xml">testContext.xml
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap.properties&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;systemPropertiesModeName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;SYSTEM_PROPERTIES_MODE_OVERRIDE&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.ContextSourceEc2InstanceLaunchingFactoryBean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;awsKey&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.key}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;awsSecretKey&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.secret.key}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;imageName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.ami}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;groupName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.security.group}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;keypairName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.keypair}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;base&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;dc=jayway,dc=se&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${userDn}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${password}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span>
  <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.LdapTemplate&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>We are referring to <code>ldap.properties</code> for the actual settings:</p>
<pre>
userDn=cn=admin,dc=jayway,dc=se
password=secret
base=dc=jayway,dc=se
aws.ami=ami-56ec083f
aws.keypair=spring-ldap-keypair
aws.security.group=spring-ldap
</pre>
<p>The referenced AMI is a public image specifically set up for our test cases. It has OpenLDAP installed and has been pre-populated with the test data that our test cases expect.</p>
<p>Note that we are not specifying any property value for <code>aws.key</code> and <code>aws.secret.key</code>, as this is the Amazon account access information. That will be the account settings of the individual developer and should be supplied at runtime using system properties (e.g. <code>mvn -Daws.key=xxxxxxx -Daws.secret.key=xxxxxx test</code>).</p>
<h3>Performing the Test</h3>
<p>Now all we need to do is use Spring's automated test support to start our test:</p>
<pre class="java">SomeLdapITest.<span style="color: #006600;">java</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span>locations = <span style="color: #66cc66;">&#123;</span> <span style="color: #ff0000;">&quot;testContext.xml&quot;</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SomeLdapITest <span style="color: #000000; font-weight: bold;">extends</span> AbstractJUnit4SpringContextTests <span style="color: #66cc66;">&#123;</span>
  @Autowired
  <span style="color: #000000; font-weight: bold;">private</span> LdapTemplate tested;
&nbsp;
  @Test
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testSomething<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">// Use the automatically injected LdapTemplate instance to perform a test.</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<h3>Set to Go</h3>
<p>With the above you should be all set to go to start using this powerful approach to integration testing. The actual code is available with the 1.3.0.RC1 release of Spring LDAP; links to downloads and documentation available <a href="http://www.springframework.org/ldap">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Among the Clouds</title>
		<link>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/</link>
		<comments>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 08:53:26 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[typica]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=77</guid>
		<description><![CDATA[One of the major challenges we've been facing in the Spring LDAP project is to make certain that the library works together with different LDAP servers. Different servers behave differently in certain situations; some functionality might only be supported on select servers, etc. In the ideal situation we would run our automated test suite against [...]]]></description>
			<content:encoded><![CDATA[<p>One of the major challenges we've been facing in the <a title="Spring LDAP" href="http://springframework.org/ldap" target="_blank">Spring LDAP</a> project is to make certain that the library works together with different LDAP servers. Different servers behave differently in certain situations; some functionality might only be supported on select servers, etc. In the ideal situation we would run our automated test suite against a multitude of target platforms for each change made to the code. Each developer would be able to run the test suite locally against each of these platforms, and the <a href="http://build.springframework.org:8085/browse/LDAP" target="_blank">continuous integration server</a> would automatically run them on each commit. This is the key element to automated testing: the automated tests must be relevant, and they must be quickly and easily run at any time, by any member of the team (or - in this case, being an open source project - by anyone that might have checked the source out from subversion). These conditions are imperative for any type of automated tests - if the conditions are not fulfilled the tests will not be run at all and consequently they will die.</p>
<p>In the perfect world, each developer would at all times have access to a server park with all of these different server versions installed. Reality is however almost always a different question: Being an Open Source project with limited funding and developers located throughout the world this has been impossible for us, up until now. You're probably already guessing: The answer is in the Clouds.</p>
<p>Having used <a href="http://www.amazon.com/gp/browse.html?node=201590011" target="_blank">Amazon EC2</a> in a couple of customer projects, we suddenly realized this is the answer to our problems. For those of you not completely familiar with the concept, the general idea of Amazon EC2 is that you configure one or several <strong>machine images</strong>, installing whatever software and data you might need on each image. You will then start an <strong>instance</strong> from one of these pre-configured images, which will in effect start up a virtual computer somewhere in the amazon cloud, a computer that will then be yours to play around with in any way you might like until you're finished with it and just shut the instance down. All of this is available at a very reasonable pricing - you pay only (a very modest amount) for the time that your instances have been running.</p>
<p>The concept suits us perfectly: we want a number of isolated environments, each with a known start state where we can run our test suite against a particular server setup. So that's what we've started to do: we have now created an EC2 image with an Open LDAP installation, pre-loaded with the data that our test cases expect. We then devised support classes to have the JUnit test cases automatically start an appropriate instance (using the excellent <a href="http://code.google.com/p/typica/" target="_blank">typica</a> library), run the tests against the started virtual machines, and shut down the instance after the tests are finished (regardless of the outcome - we don't want any stray instances running around costing us money <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ). We still have some more work to do with setting up more images for other server setups, but we're hoping to get that work going as we move on...</p>
<p>I'm planning to dig a little bit deeper into the details of the setup and the code involved in a later post. In the meantime: if you're really interested, feel free to check the code out from the <a href="https://springframework.svn.sourceforge.net/svnroot/springframework/spring-ldap/trunk/mvn-build" target="_blank">svn repo</a> and have a look at what we've done so far. The relevant code for this is in the test/integration-tests-openldap directory.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Behaviour Driven Development</title>
		<link>http://blog.jayway.com/2008/02/01/behaviour-driven-development/</link>
		<comments>http://blog.jayway.com/2008/02/01/behaviour-driven-development/#comments</comments>
		<pubDate>Fri, 01 Feb 2008 11:38:33 +0000</pubDate>
		<dc:creator>Andreas Ronge</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3392</guid>
		<description><![CDATA[Test Driven Development is a well established programming technique for creating high quality software. It is less known, however, that TDD is not only a programming technique but also a design methodology. The main goal of Behaviour Driven Development, a TDD based methodology, is to identify behaviours in both the analysis and the design phases. [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Test Driven Development is a well established programming technique for creating high quality software. It is less known, however, that TDD is not only a programming technique but also a design methodology.<br />
</strong></p>
<p>The main goal of Behaviour Driven Development, a TDD based methodology, is to identify behaviours in both the analysis and the design phases.<br />
In BDD [1] the test code looks more like a specification of behaviours than a test of the production code.</p>
<h2>Test Driven Development </h2>
<p>TDD can be summarized in one rule:<br />
“Writing code is only allowed if you have a failing unit test”. </p>
<p>The TDD development cycle:<br />
   1. Write a unit test<br />
   2. Run all tests and make sure the new one fails<br />
   3. Implement the simplest possible solution in order to make the test pass<br />
   4. Refactor the code. All tests must pass after the refactoring has been done.<br />
   5. Repeat - write a new unit test </p>
<h3>Problems:</h3>
<ul>
<li>	Unit	tests	suggest	a	strong	relationship	between	test	class	and	implementation<br />
class. Each class or method usually has a corresponding test class or test meth-<br />
od. This causes a high coupling between the class under test and the test case.<br />
It also means that we focus too early on the implementation details, instead of<br />
doing the design first.
<li>	Unclear	definition	of	granularity	of	units.	A	common	mistake	is	to	mix	up	unit test with integration tests - which may require complex setup of several com-<br />
ponents (like a database). Having a high coupling between test code and the<br />
implementation is a serious problem when later on refactoring is needed. In-<br />
stead one should use mock objects to explore interactions between objects.
<li>	Limitations	on	mock	objects	may	have	too	big	an	impact	on	the	design.	We<br />
often have to stop using the private, static and final keywords. This problem was<br />
discussed in the previous issue of JayView - Mocking Static Methods.
</ul>
<h2>The Marriage of Component<br />
Specification with Unit Test </h2>
<p>BDD has a similar development cycle, but instead of writing tests before coding you<br />
write specifications before coding.<br />
A specification consists of a description of behaviours which are expressed within a<br />
context. Behaviours become self-verifying by writing (coding) expectations in the<br />
form of examples. The specification is written in an executable form so that we can<br />
generate a readable specification and verify that its expectations are valid. </p>
<h3>Example </h3>
<p>For example let’s write a specification for a stack. We start by identifing its contexts,<br />
which are: “empty”, “neither empty nor full”, “full”. Example of behaviours for the<br />
empty context are: “should be empty”, “should not be empty after a push”. For each<br />
of those one continue to write expectations. Like TDD you specify a small set of<br />
behaviours at a time then implement it - short iterations.<br />
Let’s show how this can be done using standard JUnit since it is a well known<br />
tool. JUnit is not a good tool for doing BDD since it was only designed for doing<br />
testing. A more suitable tool is for example JDave [4] or RSpec [2] which let you<br />
create much more readable specification. (The analysis part of RSpec is shown in<br />
the next section). </p>
<pre>// The enclosed annotation makes JUnit run all inner classes as tests
@RunWith(org.junit.runners.Enclosed.class)
public class StackTest {
    public static class EmptyStack {
        private Stack stack;
        @Before
        public void before() {
            stack = new Stack();
        }
        @Test
        public void shouldBeEmpty() {
            assertTrue(stack.isEmpty());
        }
        @Test
        public void shouldNotBeEmptyAfterAPush() {
            stack.push(“Some value”);
            assertFalse(stack.isEmpty());
        }
        // ...
    }
    public static class NeitherEmptyNorFullStack {
        private Stack stack;
        @Before
        public void before() {
            stack = new Stack();
            stack.push(“x”);
        }
        @Test
        public void shouldAddToTheTopWhenSentPush() {
            stack.push(“y”);
            assertEquals(“y”, stack.peek());
        }
        // ...
    }
}
</pre>
<p>By replacing the word “test” with “should” and organizing tests around behaviours it<br />
becomes clear that we are using BDD to drive the design.<br />
This format also allows us to generate an even more readable specification by using<br />
for example the junitreport ant task with a custom style sheet that extracts the bold<br />
words. A proper BDD tool would have this ability built in. I believe this specification<br />
is much better than the (class) javadoc that are often missing or incorrect.<br />
As shown above we keep specification and test together in an executable unit. This<br />
approach can also be used at a system level. </p>
<h2>The Marriage of Application<br />
Requirements with Acceptance Tests </h2>
<p>Requirements and acceptance tests are captured using a template containing a story<br />
and one or more scenarios.<br />
<strong>As a</strong> Role, <strong>I want</strong> Feature, <strong>So that</strong> Benefit<br />
Scenario1: <strong>Given</strong> ... <strong>When</strong> ... <strong>Then</strong><br />
Scenario2 ...<br />
A story’s behaviour is its acceptance criteria - the scenarios. By using the template<br />
above we can collaborate on stories with customers. This is nothing new, it is just<br />
one way of doing analysis.<br />
What is new is that in BDD the specification is written down in an executable<br />
unit in order to have self-verifying tests. The Ruby RSpec tool has a slightly different<br />
approach. It can treat specification written in plain english as an executable unit. </p>
<h3>An example of a story:</h3>
<p>Story: transfer to cash account<br />
<strong>As a</strong> savings account holder<br />
<strong>I want</strong> to transfer money from my savings account<br />
<strong>So that</strong> I can get cash easily from an ATM<br />
Scenario: savings account is in credit<br />
<strong>Given</strong> my savings account balance is 100<br />
And my cash account balance is 10<br />
<strong>When</strong> I transfer 20 from my savings account to my cash account<br />
<strong>Then</strong> my savings account balance should be 80<br />
And my cash account balance should be 20<br />
Scenario: savings account is overdrawn<br />
<strong>Given</strong> my savings account balance is -20<br />
And my cash account balance is 10<br />
<strong>When</strong> I transfer 20 from my savings account to my cash account<br />
<strong>Then</strong> my savings account balance should be -20<br />
And my cash account balance should be 10</p>
<p>To perform verification on this specification we create an interpreter where we de-<br />
fine reusable test steps. </p>
<pre>class AccountSteps < Spec::Story::StepGroup
  steps do |define|
    define.given("my $account account balance is $balance") do |account,
balance|
      @accounts ||= {} # creates a new hash if @accounts is nil
      @accounts[account] = Account.new(balance.to_f)
    end
    define.then("my $account account balance should be $amount") do |account,
amount|
      @accounts[account].balance.should == amount.to_f
    end
    define.when("I transfer $amount from my $from account to my $to account")
do |amount, from, to|
       @accounts[from].transfere_to(@accounts[to], amount.to_f)
    end
  end
end
</pre>
<p>To run it we need to tell which steps are using what story:</p>
<pre>runner = Spec::Story::Runner::PlainTextStoryRunner.new(filename-of-the-story)
runner.steps << AccountSteps.new
runner.run </pre>
<p>RSpec matches each line in the story with the defined test steps. The code inside the<br />
define block will be executed if a match is found.<br />
For example, when the story runner reads the line “Given my savings account bal-<br />
ance is 100” it will execute </p>
<pre>@accounts['savings'] = Account.new("100".to_f).
</pre>
<p>That means a new account object is created and stored in the accounts hash. </p>
<p>Still stuck with Java ? Psst, you can use JRuby [5] to test and mock Java<br />
objects. For example, try the JtestR [6] tool which also integrates nicely<br />
with ant, maven and Buildr [3]. </p>
<h2>Conclusions</h2>
<p>There is not a big difference between TDD and BDD if TDD is used  correctly. TDD<br />
often causes brittle test code - a small change in the  production code may cause a<br />
major change in the test code. BDD gives the possibility of structuring tests to make<br />
them “refactoring friendly”. This is accomplished by organizing tests in small focused<br />
examples of  behaviours.<br />
People are not always aware that TDD is able to drive the design. By not  thinking<br />
in terms of tests but instead describing the what and why of  behaviours, it becomes<br />
clear that BDD is a methodology for analysis and design. </p>
<h2>References</h2>
<p>[1] BDD - <a href="http://behaviour-driven.org/">http://behaviour-driven.org/</a><br />
[2] RSpec - <a href="http://rspec.rubyforge.org/">http://rspec.rubyforge.org/</a><br />
[3] Buildr - <a href="http://buildr.rubyforge.org/">http://buildr.rubyforge.org/</a><br />
[4] JDave - <a href="http://www.jdave.org/">http://www.jdave.org/</a><br />
[5] JRuby - <a href="http://jruby.codehaus.org/">http://jruby.codehaus.org/</a><br />
[6] JtestR - <a href="http://jtestr.codehaus.org">http://jtestr.codehaus.org</a></p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/02/01/behaviour-driven-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

