<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Jayway Team Blog » Testing</title>
	
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Mon, 16 Aug 2010 05:54:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/jayway/posts/testing" /><feedburner:info uri="jayway/posts/testing" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Awaitility – Java DSL for easy testing of asynchronous systems</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/-2IHgAYvOyU/</link>
		<comments>http://blog.jayway.com/2010/07/20/awaitility-java-dsl-for-easy-testing-of-asynchronous-systems/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 08:26:15 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[open source]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5844</guid>
		<description><![CDATA[Introduction Testing asynchronous systems is hard. Not only does it require handling threads, timeouts and concurrency issues, but the intent of the test code can be obscured by all these details. Awaility is a DSL that allows you to express expectations of a asynchronous system in a concise and easy to read manner. Simple example [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Testing asynchronous systems is hard. Not only does it require handling threads, timeouts and concurrency issues, but the intent of the test code can be obscured by all these details. Awaility is a DSL that allows you to express expectations of a asynchronous system in a concise and easy to read manner.</p>
<h2>Simple example</h2>
<p>So let's assume that we send an "add user" message to our asynchronous system like this:</p>
<pre class="java">&nbsp;
publish<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;John Doe&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>In your test case Awaitility can help you to easily verify that the database has been updated. In its simplest form it may look something like this:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>newUserIsAdded<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Awaitility will now block the test execution and wait until the new user is added to the database. <code>newUserIsAdded</code> is a method that you implement yourself in your test case. It specifies the condition that must be fulfilled in order for Awaitility to stop waiting.</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> Callable&lt;Boolean&gt; newUserIsAdded<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> <span style="color: #000000; font-weight: bold;">new</span> Callable&lt;Boolean&gt;<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;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ABoolean+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Boolean</span></a> call<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;">return</span> userRepository.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> == <span style="color: #cc66cc;">1</span>; <span style="color: #808080; font-style: italic;">// The condition that must be fulfilled</span>
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>By default Awaitility will wait for 10 seconds and if the size of the user respository is not equal to 1 during this time it'll throw a <code>TimeoutException</code> failing the test. If you want a different timeout you can define it like this:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">atMost</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span>, SECONDS<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>newUserWasAdded<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Better reuse</h2>
<p>Awaitility also supports splitting up the condition into a supplying and a matching part for better reuse. The example above can also be written as:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span> userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>The <code>userRepositorySize</code> method is now a Callable of type Integer:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> Callable&lt;Integer&gt; userRepositorySize<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> <span style="color: #000000; font-weight: bold;">new</span> Callable&lt;Integer&gt;<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;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> call<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;">return</span> userRepository.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// The condition supplier part</span>
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p><code>equalTo</code> is a standard <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> matcher specifiying the matching part of the condition for Awaitility.</p>
<p>Now we could reuse the <code>userRepositorySize</code> in a different test. E.g. let's say we have a test that adds three users at the same time:</p>
<pre class="java">&nbsp;
publish<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 1&quot;</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 2&quot;</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 3&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>We now reuse the <code>userRepositorySize</code> supplier and simply update the Hamcrest matcher:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span> userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Reduce verboseness</h2>
<p>Since Java is so verbose Awaitility also provides a way achieve the same result by building up the supplier part without defining a Callable:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span> callTo<span style="color: #66cc66;">&#40;</span>userRepository<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p><code>callTo</code> is method in Awaitility which you can use to define the suppling part inline in the await statement. Which option you like best depends on the use case and readability.</p>
<h2>More features</h2>
<p>Awaitility uses polling to check if a condition is fulfilled. You can easily specify a polling interval and poll delay (the delay before the first poll commits):</p>
<pre class="java">&nbsp;
with<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">pollInterval</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">400</span>, MILLISECONDS<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">and</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">pollDelay</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, SECONDS<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">await</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">forever</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>somethingHappens<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>In some cases it's also useful to create named awaits for example if you need multiple awaits in one test. A naive example:</p>
<pre class="java">&nbsp;
publish<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 1&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
await<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;user 1&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, is<span style="color: #66cc66;">&#40;</span>equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
publish<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 2&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
await<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;user 2&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, is<span style="color: #66cc66;">&#40;</span>equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>So if the first await statement fails the <code>TimeoutException</code> will indicate that it was the "user 1" statement that failed and so on.</p>
<h2>Conclusion</h2>
<p>We hope that you find Awaitility easy to use when you need to synchronize asynchronous behaviour in Java. However be aware that since it uses polling to verify that the condition is fulfilled it's not recommended to use it for precise performance testing. In these cases it could be better to use an AOP framework such as AspectJ and leverage on its compile-time weaving. </p>
<p>Please visit our <a href="http://code.google.com/p/awaitility/">homepage</a> for more info and downloads.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/-2IHgAYvOyU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/07/20/awaitility-java-dsl-for-easy-testing-of-asynchronous-systems/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2010/07/20/awaitility-java-dsl-for-easy-testing-of-asynchronous-systems/</feedburner:origLink></item>
		<item>
		<title>Developing JMeter plugins using Maven</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/fnSgJFlGL9Y/</link>
		<comments>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 15:44:22 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[jmeter]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5814</guid>
		<description><![CDATA[I have been using JMeter for load testing and I needed to create a custom plugin to handle parsing JSON results but I couldn't find a simple guide how to do this. I wanted a simple solution that didn't require manual installation in my repository or a repository manager such as Nexus. ]]></description>
			<content:encoded><![CDATA[<p>I have been using <a href="http://jakarta.apache.org/jmeter/">JMeter</a> for load testing and I needed to create a custom plugin to handle parsing JSON results but I couldn't find a simple guide how to do this. I wanted a simple solution that didn't require manual installation in my repository or a repository manager such as <a href="http://nexus.sonatype.org/">Nexus</a>. </p>
<h3>Building the plugin</h3>
<p>Building a plugin using maven is easy, simply add the following to your pom:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;properties<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;jmeter</span>.home<span style="font-weight: bold; color: black;">&gt;</span></span>installation directory of jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/jmeter</span>.home<span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/properties<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependencies<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>jmeter-core<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>2.3.4<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>system<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>${jmeter.home}/lib/ext/ApacheJMeter_core.jar<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>jmeter-jorphan<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>2.3.4<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>system<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>${jmeter.home}/lib/jorphan.jar<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependencies<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<p>You probably want to put <code>jmeter.home</code> in your <code>settings.xml</code> instead.</p>
<h3>Testing the plugin</h3>
<p>Whenever I develop something I want to have a quick build/test cycle. In this case I want to to start the JMeter UI without having to update the JMeter installation or any other manual work. I didn't get <a href="http://mojo.codehaus.org/chronos-maven-plugin/">chronos</a> to add my plugin to the UI. It seems chronos copied the jar files to <code>JMETER_HOME/lib/junit</code> and this probably works for running an already created test, but not for creating the test. I also failed to the the <a href="http://mojo.codehaus.org/exec-maven-plugin/index.html">maven exec plugin</a> to create the command line arguments I needed. Instead I added a small ant script to start JMeter:</p>
<pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;build<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.maven.plugins<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>maven-antrun-plugin<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;tasks<span style="font-weight: bold; color: black;">&gt;</span></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;runtime_classpath&quot;</span>
           <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;maven.runtime.classpath&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
          <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;exec</span> <span style="color: #000066;">executable</span>=<span style="color: #ff0000;">&quot;${jmeter.home}/bin/jmeter.bat&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
            <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;arg</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;-Jsearch_paths=${runtime_classpath}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
          <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/exec<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/tasks<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/build<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<p>To run the jmeter gui simply run <code>mvn antrun:run</code>. This only works for Windows, I leave other platforms as an exercise to the reader <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . </p>
<h3>Using the plugin</h3>
<p>I ended up copying the plugin jar and dependencies to the JMeter installation and used then this modified JMeter distribution when performing the tests. The reason was that I didn't have maven installed on some of the test clients. To copy dependencies you can use <a href="http://maven.apache.org/plugins/maven-dependency-plugin/copy-dependencies-mojo.html">mvn dependency:copy-dependencies</a>.<br />
If you want to run JMeter using maven you probably want to look at <a href="http://mojo.codehaus.org/chronos-maven-plugin/index.html">chronos</a> (although it is not released it seems to work fine):</p>
<ul><a href="http://gabenell.blogspot.com/2009/11/using-maven-chronos-without-external.html">Using Maven Chronos Without an External JMeter Install</a></ul>
<ul><a href="http://blogs.atlassian.com/developer/2009/10/automated_performance_testing_using_jmeter_and_maven.html">Automated performance testing using JMeter and Maven</a></ul>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/fnSgJFlGL9Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/</feedburner:origLink></item>
		<item>
		<title>How-to get a large C: drive for Windows on Amazon</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/31ILlfYi3js/</link>
		<comments>http://blog.jayway.com/2010/03/31/how-to-get-a-large-c-drive-for-windows-on-amazon/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 09:08:11 +0000</pubDate>
		<dc:creator>Adam Skogman</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[ebs]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5238</guid>
		<description><![CDATA[Amazon has excellent Windows support these days. Many time you'd like a larger C: drive than the 30 GB that come standard with the Amazon images. Here is how you enlarge the boot drive to 100 GB.]]></description>
			<content:encoded><![CDATA[<p>Amazon has excellent Windows support these days, and computers boot up from EBS. Drives are therefor both fast and robust. However, many time you'd like a larger C: drive than the 30 GB that come standard with the Amazon images. Here is how you enlarge the boot drive!</p>
<p>First step is to boot an instance. You need the command line tools for this, as neither the AWS Management Web Console nor ElasticFox currently supports this right now (note to developers - please add!).</p>
<pre>
ec2-run-instances --region eu-west-1 \
     -K pk-YOURKEYHERE.pem \
     -C cert-YOURCERTHERE.pem \
     <strong>-b '/dev/sda1=:100' \</strong>
     ami-d7a78ca3 \
     -g my-security-group -g common-security-group \
     -t m1.large \
     -k thekeyhere \
     --disable-api-termination \
     --instance-initiated-shutdown-behavior stop \
     -z eu-west-1a
</pre>
<ul>
<li>The command is <strong>ec2-run-instances</strong> with an <strong>'s'</strong> in the end. There is another command in the API without the s, which doesn't work.</li>
<li><strong>-b</strong> is the most important flag here. It says to make the boot disk (/dev/sda is Linux speek for C:) 100 GB, despite what the AMI manifest says (which is 30 GB).</li>
<li><strong>ami-d7a78ca3</strong> is the Windows image, in this case a 64bit Windows 2008.</li>
<li>-g security-group you should add as many as you like. Remember to think these through, since you cannot change which groups an instance belongs to.</li>
<li>The flags <strong>--disable-api-termination --instance-initiated-shutdown-behavior stop</strong> are really nice, because that make sure you cannot accidentally terminate the instance, making the harddrive disappear.</li>
<li>Note that I'm running in the EU region here.</li>
</ul>
<p>Ok, so now you have a running Windows server. Once it has booted, you log on using remote desktop (well, as soon as you have the generated password, which takes 15 min). PLease note that the C: drive will show up as 30 GB at this point. The partition is still only 30 GB, even if the virtual harddrive is 100 GB.</p>
<ol>
<li>Go into the windows management console. Go to <strong>disk management</strong>.</li>
<li><strong>Right-click</strong> on the C: drive. Choose <strong>Extend volume</strong> from the context menu.</li>
<li>In the wizard that pops up, just accept the defaults, and click finish.</li>
</ol>
<p>Done! The change is instant (no reboot or anything), and your system drive C: is now 100 GB.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/31ILlfYi3js" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/31/how-to-get-a-large-c-drive-for-windows-on-amazon/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2010/03/31/how-to-get-a-large-c-drive-for-windows-on-amazon/</feedburner:origLink></item>
		<item>
		<title>Continuos Integration for XCode projects</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/JLi5fPJzsHQ/</link>
		<comments>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 17:35:59 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[hudson]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4624</guid>
		<description><![CDATA[Continuos Integration is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://martinfowler.com/articles/continuousIntegration.html" title="Continuous Integration">Continuos Integration</a> is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you and your team will be notified right away.
</p>
<p>
This is the second part of the blog post I wrote about <a href="http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/">TDD in XCode</a>. Make sure you've followed that tutorial before continuing here, or at least have a project of your own with OCUnit tests ready.
</p>
<p>
The server which we'll use is called <a href="https://hudson.dev.java.net/" title="Hudson">Hudson</a> and is very popular in the Java community. It does not readily support XCode projects but it does allow shell commands, so we'll use that to make our Calculator project compatible. We also want to fetch new versions of the source code as soon as it's checked in. We'll be a bit fancy and use <a href="http://git-scm.com/" title="Git - Fast Version Control System">Git</a> as source control software.	Here's a summary of what we want to do:
</p>
<ol>
<li>Download and install the Hudson continuos integration server</li>
<li>Download, install and setup the Git source control software as well as the Git plugin for Hudson</li>
<li>Download and install a script that converts OCUnit test results to JUnit format</li>
<li>Setup a new job in Hudson that checks out our XCode project and builds and tests it</li>
<li>Set up a notification and try it out</li>
</ol>
<h2>Downloading and Installing Hudson</h2>
<p>
In order to keep the instructions in this tutorial simple, we will have the source code repository and the build server itself on localhost. In real life you'll probably want to setup a dedicated machine.</p>
<p>Head over to the <a href="https://hudson.dev.java.net/" title="Hudson">Hudson web site</a> and download your copy of the server. Follow their included installation instructions, it's quite simple. Once you have Hudson up and running you can visit <a href="http://localhots:8080">http://localhost:8080</a> to see the welcome screen. By the way, when you're ready to install Hudson on a real remote server I recommend running it as a Servlet inside <a href="http://tomcat.apache.org/" title="Apache Tomcat - Welcome!">Apache Tomcat</a> instead.
</p>
<h2>Downloading and Setting Up Git</h2>
<p>Next we want to install Git. There are several ways to install it. The simplest might be to use <a href="http://code.google.com/p/git-osx-installer/">the OS X installer</a>, but I personally prefer <a href="http://www.macports.org/" title="The MacPorts Project">MacPorts</a>. Either way, go ahead and install it and make sure that you can use the "git" command from Terminal.app when you're done.
</p>
<p>
In the Terminal, change directory to your XCode project folder and type:</p>
<pre class="brush:bash">
		git init
	</pre>
<p>You now have a working source code repository in your project folder. Neat. Before you continue create a text file called <em>.gitignore</em> and let it contain:</p>
<pre class="brush:plain">
		build/*
		*.pbxuser
		*.mode1v3
		.DS_Store
		test-reports/*
	</pre>
<p>	That's a listing of the files and folders that should not be version controlled, since they are temporary or just used for XCode. Feel free to add any other files that you think only should be present locally. Now add all files (that aren't ignored) using:</p>
<pre class="brush:bash">
		git add *
	</pre>
<p>	and finally commit them to a first version using:</p>
<pre class="brush:bash">
		git commit -m "Initial import"
	</pre>
</p>
<h2>Fetching the Script</h2>
<p>
We need to fetch one more thing, <a href="http://github.com/ciryon/OCUnit2JUnit/blob/master/ocunit2junit.rb">ocunit2junit.rb</a>, which is a little Ruby script that I wrote. Since you now have git, you can also download it using git (or <em>clone the repo</em>, which is the correct term). Change directory to /tmp and then type like this:</p>
<pre class="brush:bash">git clone git://github.com/ciryon/OCUnit2JUnit.git</pre>
<p>Copy the script from /tmp/OCUnit2JUnit/ anywhere, like to /usr/local/bin/. Make sure it's executable by typing <em>chmod +x ocunit2junit.rb</em>.</p>
<p>The script will parse output from xcodebuild (the console command for building your XCode project) and look for output from OCUnit. The test results (success, failure, time passed etc) will be saved in the "test-reports" folder in the same XML format that JUnit uses. This also happens to be a format that Hudson understands.
</p>
<h2>Setting Up Hudson</h2>
<p>
Now head back to your Hudson welcome screen. Select <em>Manage Hudson</em>, <em>Manage plugins</em> and check "Hudson GIT plugin" under <em>Available</em>. Hudson will automatically download and install the plugin. Afterwards just restart Hudson.
</p>
<p>
We're ready to create a job in Hudson for our project. From the main screen select "New job", Build a free-style software project and call it "Calculator". There are some settings which you should fill in:</p>
<ul>
<li>
			Select to use git as source code management tool. The URL should be the file path to your project, like:
<pre class="brush:bash">/Users/youruser/XCodeProjects/Calculator/</pre>
</li>
<li>
			Select to poll SCM with Schedule:
<pre class="brush:bash">* * * * *</pre>
<p>			That means it'll check every minute if there are changes. If you want to check less often, do that.
		</li>
<li>
			Add new build step and select to execute shell. Use this command (make sure to point to the version of the iPhone SDK you want to use):</p>
<pre class="brush:plain">xcodebuild -target "UnitTests" -sdk /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.2.sdk/ -configuration "Debug" | /usr/local/bin/ocunit2junit.rb</pre>
</li>
<li>
			Select to also publish a JUnit test result report and the Test report XMLs reside at
<pre class="brush:plain">test-reports/*.xml</pre>
</li>
</ul>
<h2>Trying it out</h2>
<p>This is the moment of truth. Try to change your CalculatorTest.m so that one of the test cases fail. Type:</p>
<pre class="brush:bash">
	git -a commit CalculatorTest.m "Broke the test, on purpose"
</pre>
<p>and see what happens. If all goes well, and you have entered everything correctly,  Hudson should automatically notice there's a new version available, build it and try to run the test suite. Check the results and how it reports the test failure. Nice, eh? Fix the error and commit the test class again to see how Hudson reacts.
</p>
<p>
There are many settings, plugins and cool things to try out in Hudson. Go into Manage Hudson-> Configure system and setup your email settings, to allow Hudson to send mail. Then go back to configure your Calculator job and at the bottom select E-mail Notification. Enter your own email address and see how it works after you commits a file that breaks the build. If you don't want a mail, you can get an instant message, or perhaps have the server play a loud annoying sound? Everyone in your team should be aware of when a build fails, so it can be fixed right away. This is one of the great advantages of having a continuos integration server.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/JLi5fPJzsHQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/</feedburner:origLink></item>
		<item>
		<title>Maven, FindBugs and Dashboard Reports</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/iFPI6J-V04A/</link>
		<comments>http://blog.jayway.com/2010/01/29/maven-findbugs-and-dashboard-reports/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 20:02:59 +0000</pubDate>
		<dc:creator>Davor Crnomat</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4571</guid>
		<description><![CDATA[There are a few simple steps to get nice graphic presentations of FindBugs results using Maven.

First, to enable FindBugs reporting in Maven, just add report section to your pom files, something like example below, but of course, you can do your own configuration.]]></description>
			<content:encoded><![CDATA[<p>There are a few simple steps to get nice graphic presentations of FindBugs results using Maven.</p>
<p>First, to enable FindBugs reporting in Maven, just add report section to your pom files, something like example below, but of course, you can do your own configuration.</p>
<pre class="brush:xml">
&lt;reporting&gt;
  &lt;plugins&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
      &lt;artifactId&gt;findbugs-maven-plugin&lt;/artifactId&gt;
      &lt;version&gt;2.3&lt;/version&gt;
      &lt;configuration&gt;
        &lt;excludeFilterFile&gt;exclude.xml&lt;/excludeFilterFile&gt;
        &lt;findbugsXmlOutput&gt;true&lt;/findbugsXmlOutput&gt;
        &lt;findbugsXmlWithMessages&gt;true&lt;/findbugsXmlWithMessages&gt;
        &lt;threshold&gt;Low&lt;/threshold&gt;
        &lt;effort&gt;Max&lt;/effort&gt;
        &lt;xmlOutput&gt;true&lt;/xmlOutput&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
  &lt;/plugins&gt;
&lt;/reporting&gt;
</pre>
<p>Then you can just use command <strong>mvn site </strong>if you want to generate<strong> </strong>more comprehensive project information or <strong>mvn findbugs:findbugs </strong>for only FindBugs reports.</p>
<p>Finally use <strong>mvn dashboard:dashboard</strong> to generate charts.</p>
<p>Voila. We have got nice graphic reports.<br />
Well, not so nice. We have bugs we need to fix.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/01/findbugs_report.jpg" rel="lightbox"><img class="size-full wp-image-4572 alignleft" title="findbugs_report" src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/01/findbugs_report.jpg" alt="FindBugs report charts" width="621" height="686" /></a></p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/iFPI6J-V04A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/29/maven-findbugs-and-dashboard-reports/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2010/01/29/maven-findbugs-and-dashboard-reports/</feedburner:origLink></item>
		<item>
		<title>The easy way to test Android applications</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/omuyxWxESl8/</link>
		<comments>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 09:44:44 +0000</pubDate>
		<dc:creator>Renas Reda</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4536</guid>
		<description><![CDATA[I’m going to guess that most of you know what instrumentation is. In the event that you don't, instrumentation is a feature in which specific monitoring of the interactions between an application and the system is made possible. Instrumentation also makes it possible to write test cases that interact with the application. The problem with [...]]]></description>
			<content:encoded><![CDATA[<p>I’m going to guess that most of you know what instrumentation is. In the event that you don't, instrumentation is a feature in which specific monitoring of the interactions between an application and the system is made possible. Instrumentation also makes it possible to write test cases that interact with the application. The problem with instrumentation, however, is that it is incredibly hard to write solid test cases for applications bigger than the typical “Hello World!” application. A tremendous amount of technical details must be taken into account in order to write a good test case. Often, developers quickly realize that it will take almost as long to write a comprehensive test case as it took to write the whole application. I, myself, came to recognize the very same thing when I first started looking into how to use instrumentation tests with the android application project that I’m currently working on.</p>
<p>I soon came to understand that I would not be able to take advantage of all the wonderful possibilities that instrumentation offers. The reason for that is quite simple; the application that we are in the process of developing is not only extensive but also complicated with multiple activities, self-defined intents, and hundreds of views that also include scrollable lists. It would not make sense for me to spend a month writing one single test case that would only take 20 seconds to test manually. That is how Robotium-Solo was born. I needed a test framework that would help me write good and powerful test cases that emulated real users. The test case should be able to do what a real user does: click on anything that is clickable, look for irregularities, automatically move from activity to activity, etc. More importantly, I should not have to spend more than 10 minutes writing a test case that involves more then one activity.</p>
<p>With the help of Robotium-Solo a test case spanning over multiple activities could look like this:</p>
<pre class="brush:java">public void testTextIsSaved() throws Exception {
   solo.clickOnText("Other");
   solo.clickOnButton("Edit");
   assertTrue(solo.searchText("Edit Window"));
   solo.enterText(0, "Some text for testing purposes")
   solo.clickOnButton("Save");
   assertTrue(solo.searchText("Changes have been made successfully"));
   solo.clickOnButton("Ok");
   assertTrue(solo.searchText("Some text for testing purposes"));
}
</pre>
<p>As you can see, I don’t have to specify any technical details or tell Robotium-Solo where to look for something, such as scrolling down a list when needed. It handles the above and more all on its own.</p>
<p>If you are interested in writing test cases of similar nature have a look at http://www.robotium.org. It makes writing powerful test cases a breeze.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/omuyxWxESl8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/</feedburner:origLink></item>
		<item>
		<title>Test Driven Development in XCode</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/9v3q6q61o7o/</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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/9v3q6q61o7o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/</feedburner:origLink></item>
		<item>
		<title>Classloader Deep-Cloning without Serialization</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/WuZV9HafEC0/</link>
		<comments>http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 11:46:14 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[classloader]]></category>
		<category><![CDATA[deep-cloning]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[manipulate]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4000</guid>
		<description><![CDATA[Background In PowerMock we're using a custom classloader to byte-code manipulate classes that are normally not mockable to make them mockable. But when running a test case there may be some cases when the user needs to byte-code manipulate a certain class (X) in the first test method but needs to have the class unmodified [...]]]></description>
			<content:encoded><![CDATA[<h2>Background</h2>
<p>In <a href="http://www.powermock.org">PowerMock</a> we're using a custom classloader to byte-code manipulate classes that are normally not mockable to make them mockable. But when running a test case there may be some cases when the user needs to byte-code manipulate a certain class (X) in the first test method but needs to have the class unmodified in the second. For example you may want to remove the static initializer of class X in testA but in testB you want the static initializer intact. There's no standard way for a Java classloader to reload a class that has already been loaded so what to do? The solution is to execute that particular test method in a new classloader. Using this approach we can simply load X again and this time we won't modify it. In PowerMock we've also implemented a custom JUnit runner which allows us to execute certain test-methods in another classloader. Without going into too much detail the problem is that we need to execute some test methods in a new classloader as well as being able to supply and receive state between our classloaders. The end user shouldn't be aware that the unit test they're running is actually chunked up into several different JUnit test cases executed in many different classloaders.</p>
<h2>Requirements</h2>
<p>Our goal was to be able to execute any block of code in any given classloader without using any byte-code manipulation. We can't make any assumptions about the class such as it being serializable or having a default constructor. We also need the outcome of this code-block to be used by the original/invoking classloader. </p>
<h2>Solution</h2>
<p>The solution was to implement a <a href="http://code.google.com/p/powermock/source/browse/trunk/classloading/src/main/java/org/powermock/classloading/ClassloaderExecutor.java">ClassLoaderExecutor</a> which takes a <code>Runnable</code> or <code>Callable</code> and executes this code-block in any classloader. In the case of <code>Callable</code> the result from the callable invocation is cloned back to the original classloader calling the method. Let's look at an example. </p>
<p>First we define the code-block to be executed in the other classloader:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyCodeBlock <span style="color: #000000; font-weight: bold;">implements</span> Callable&lt;MyResult&gt;
	<span style="color: #808080; font-style: italic;">/*
         * All code inside this method will be executed in a different class-loader.
         */</span>
	<span style="color: #000000; font-weight: bold;">public</span> MyResult call<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>
		OperationToExecute operationToExecute = <span style="color: #000000; font-weight: bold;">new</span> OperationToExecute<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		...
		<span style="color: #000000; font-weight: bold;">return</span> operationToExecute.<span style="color: #006600;">execute</span><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>
<p>Then we simply execute this block using the <code>ClassLoaderExecutor</code>:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Instantiate the classloader where the code-block should be executed.</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AClassLoader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">ClassLoader</span></a> myClassloader = <span style="color: #000000; font-weight: bold;">new</span> MyCustomClassLoader<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Initialize the ClassLoaderExecutor with the classloader</span>
ClassLoaderExecutor classLoaderExecutor = <span style="color: #000000; font-weight: bold;">new</span> ClassLoaderExecutor<span style="color: #66cc66;">&#40;</span>myClassloader<span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">/*
 * Pass in the code-block to the ClassLoaderExecutor. The code inside
 * the call method will be executed in the &quot;myClassloader&quot;
 * and the result (MyResult) will be usable from the invoking
 * classloader (the one that called the execute method).
 */</span>
MyResult result = classLoaderExecutor.<span style="color: #006600;">execute</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MyCodeBlock<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
...
&nbsp;</pre>
<h2>How does it work?</h2>
<p>The first thing that happens when execute is called is that almost the entire object graph of the code-block is deep-cloned into the target classloader (myClassloader in the example above). The objects that are not cloned are those whose classes reside in the <code>rt.jar</code> which are always loaded by the bootstrap classloader. These objects are (in the simple cases) only referred to by a cloned object. Since we cannot make any assumptions about the class structure or hierarchy we cannot simply do deep-cloning using standard Java serialization. Neither can we clone the objects using simple reflection because how do we know which constructor to invoke when instantiating the object using the target classloader? Essentially the trick is to instantiate the class without executing any constructor at all. When this is done we iterate over all fields and instantiate and copy their values recursively. But how can you instantiate a class without invoking a constructor? Unfortunately there's no standard way of doing this. In a modern Sun JVM you can use <code>sun.reflect.ReflectionFactory</code> but it's not guaranteed that other JVM's have implemented this class. To make it more compatible we make use of the excellent <a href="http://code.google.com/p/objenesis/">Objenesis</a> framework whose sole purpose is to accommodate this across multiple JVM's from different vendors. When all state has been copied from the source to the target classloader using this approach the result of the callable operation (myResult in the example above) is cloned back from the target to the source classloader. This means that the result is directly usable from the source classloader after the execute method has finished.</p>
<h2>Conclusion</h2>
<p>This article has demonstrated one approach of executing a block of code in any given classloader using deep-cloning without serialization. There are many corner cases which we haven't dealt with here such as dealing with arrays, lists, enum, static final fields, object references etc that the <code>ClassLoaderExecutor</code> also supports. An alternative may be to use <a href="http://xstream.codehaus.org/">XStream</a> as deep-cloner to serialize the object graph to XML and de-serialize it back to  the target classloader but the approach suggested here should potentially be faster.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/WuZV9HafEC0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/</feedburner:origLink></item>
		<item>
		<title>PowerMock + TestNG = True</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/vAinj-GQYNQ/</link>
		<comments>http://blog.jayway.com/2009/12/14/powermock-testng-true/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 19:07:57 +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[testng]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3939</guid>
		<description><![CDATA[After having it on our todo list for at least a year we've finally managed to integrate PowerMock with TestNG 5.11 as of PowerMock version 1.3.5. This is a big milestone of the project since we've now demonstrated that PowerMock is decoupled from both a specific test framework and a specific mock framework. The TestNG [...]]]></description>
			<content:encoded><![CDATA[<p>After having it on our todo list for at least a year we've finally managed to integrate <a href="http://www.powermock.org">PowerMock</a> with <a href="http://www.testng.org">TestNG</a> 5.11 as of PowerMock version 1.3.5. This is a big milestone of the project since we've now demonstrated that PowerMock is decoupled from both a specific test framework and a specific mock framework. The TestNG integration still needs improvements and we're happy for all suggestions, comments or patches. </p>
<p>So how do you configure PowerMock to use TestNG? First of all follow the instructions on the <a href="http://code.google.com/p/powermock/wiki/GettingStarted">getting started</a> page which states everything you need to know to get started with or without Maven. The trick is then to specify the PowerMock object factory in the TestNG suite.xml. An example can be seen here: </p>
<pre class="brush:java">
<suite name="dgf" verbose="10" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
    <test name="dgf">
        <classes>
            <class name="com.mycompany.Test1"/>
            <class name="com.mycompany.Test2"/>
        </classes>
    </test>
</suite>
</pre>
<p>Without specifying this object factory the test will never be bootstrapped properly by PowerMock and thus will fail if any PowerMock functionality is used in the test.</p>
<h3>Example</h3>
<p>Now that we know how to bootstrap PowerMock and TestNG what does a test look like? If you're used to PowerMock there will be no surprises. As usually you have to prepare the class that is normally not testable/mockable for test using the <code>@PrepareForTest</code> annotation. Consider that we have a class like this:</p>
<pre class="brush:java">
public class ClassUnderTest {
	public void methodToTest() {
	   ..
	   final long id = IdGenerator.generateNewId();
	   ..
	}
}
</pre>
<p>When testing this class we might want to mock the static call to the IdGenerator. The full test will look like this using the Mockito extension API:</p>
<pre class="brush:java">
@PrepareForTest(IdGenerator.class)
public class MyTestClass {
    @Test
    public void demoStaticMethodMockingUsingTestNGAndMockito() throws Exception {
        mockStatic(IdGenerator.class);

        when(IdGenerator.generateNewId()).thenReturn(2L);               

        new ClassUnderTest().methodToTest();

        // Optionally verify that the static method was actually called
        verifyStatic();
        IdGenerator.generateNewId();
    }
}
</pre>
<p>Using the EasyMock API extension the test could look like this:</p>
<pre class="brush:java">
@PrepareForTest(IdGenerator.class)
public class MyTestClass {
    @Test
    public void demoStaticMethodMockingUsingTestNGAndEasyMock() throws Exception {
        mockStatic(IdGenerator.class);

        expect(IdGenerator.generateNewId()).andReturn(2L);

	replayAll();

        new ClassUnderTest().methodToTest();

        verifyAll();
    }
}
</pre>
<h3>Advanced</h3>
<p>Under the hood the PowerMock object factory also creates a proxy around the test class. This proxy adds support for creating and injecting mocks using the <code>@Mock</code> annotation and clears state created by PowerMock between each test. This means that you can create and inject mocks to your test like this:</p>
<pre class="brush:java">
@PrepareForTest(MyFinalClassExample.class)
public class MockInjectionTest {

    @Mock
    private MyFinalClassExample myExampleMock;

    @Test
    public void demoMockInjection() throws Exception {
	..
	expect(myExampleMock.myExample()).andReturn(8);
	..
    }
}
</pre>
<p>This works for both the EasyMock and Mockito API extensions. If you for some reason doesn't like that your test class is proxied you can manually extend the <code>org.powermock.modules.testng.PowerMockTestCase</code> to get the same functionality.</p>
<h3>Round up</h3>
<p>There's still much work to be done with the TestNG object factory such as getting better support for scoped injections and getting PowerMock test listeners in place. If you'd like to contribute in any way just drop us a note using the mailing list. Last but not least we would like to thank Dan Fabulich of the TestNG team for all the help making this possible.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/vAinj-GQYNQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/14/powermock-testng-true/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/12/14/powermock-testng-true/</feedburner:origLink></item>
		<item>
		<title>Untestable code with Mockito and PowerMock</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/ie8mpa_AmnQ/</link>
		<comments>http://blog.jayway.com/2009/10/28/untestable-code-with-mockito-and-powermock/#comments</comments>
		<pubDate>Wed, 28 Oct 2009 16:38:03 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2180</guid>
		<description><![CDATA[With the new release of PowerMock 1.3 we've focused a lot on getting the Mockito support up to par with the EasyMock support allowing mocking of e.g. final classes, static methods and new object construction using a Mockito-like syntax. Below you'll find some examples of how to use the Mockito extension API, aka PowerMockito. Hopefully [...]]]></description>
			<content:encoded><![CDATA[<p>With the new release of PowerMock 1.3 we've focused a lot on getting the Mockito support up to par with the EasyMock support allowing mocking of e.g. final classes, static methods and new object construction using a Mockito-like syntax. Below you'll find some examples of how to use the Mockito extension API, aka PowerMockito. Hopefully those of you used to Mockito will find PowerMock(ito) simple to use as well.</p>
<p>As always you need to add <code>@RunWith(PowerMockRunner.class)</code> at the class-level of your test in order to bootstrap PowerMock itself. The classes that are normally not mockable needs to be prepared for testability by using the <code>@PrepareForTest</code> annotation.</p>
<h3>Example #1 - Static methods</h3>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> methodToTest<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;">final</span> <span style="color: #993333;">long</span> id = IdGenerator.<span style="color: #006600;">generateNewId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   ..
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Let's say that in our test we want to mock the static call to the IdGenerator.generateNewId() and have it return 2 using the Mockito extension API. This can be achieved the following way:</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>
<span style="color: #808080; font-style: italic;">// We prepare the IdGenerator for test because the static method is normally not mockable</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span>IdGenerator.<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> MyTestClass <span style="color: #66cc66;">&#123;</span>
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> demoStaticMethodMocking<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>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
       <span style="color: #808080; font-style: italic;">/*
        * Setup the expectation using the standard Mockito syntax,
        * generateNewId() will now return 2 everytime it's invoked
        * in this test.
        */</span>
	when<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #006600;">generateNewId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span>2L<span style="color: #66cc66;">&#41;</span>;		
&nbsp;
	<span style="color: #000000; font-weight: bold;">new</span> ClassUnderTest<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">methodToTest</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Optionally verify that the static method was actually called</span>
	verifyStatic<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	IdGenerator.<span style="color: #006600;">generateNewId</span><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>Example #2 - Mock private methods (partial mocking)</h3>
<p>Partial mocking of both static and instance methods works in PowerMock regardless if the method or class is final or private. Let's say we'd like to test the "methodToTest" in isolation from the private "methodToMock" method in the example below:</p>
<pre class="java">&nbsp;
<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> PrivatePartialMockingExample <span style="color: #66cc66;">&#123;</span>
    <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> methodToTest<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> methodToMock<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;input&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <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> methodToMock<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> input<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;REAL VALUE = &quot;</span> + input;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>To achieve this we can do:</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>PrivatePartialMockingExample.<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> PrivatePartialMockingExampleTest <span style="color: #66cc66;">&#123;</span>
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> demoPrivateMethodMocking<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;">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> expected = <span style="color: #ff0000;">&quot;TEST VALUE&quot;</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> nameOfMethodToMock = <span style="color: #ff0000;">&quot;methodToMock&quot;</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> input = <span style="color: #ff0000;">&quot;input&quot;</span>;
&nbsp;
	PrivatePartialMockingExample underTest = spy<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PrivatePartialMockingExample<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">/*
	 * Setup the expectation to the private method using the method name
	 */</span>
	when<span style="color: #66cc66;">&#40;</span>underTest, nameOfMethodToMock, input<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span>expected<span style="color: #66cc66;">&#41;</span>;
&nbsp;
	assertEquals<span style="color: #66cc66;">&#40;</span>expected, underTest.<span style="color: #006600;">methodToTest</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Optionally verify that the private method was actually called</span>
	verifyPrivate<span style="color: #66cc66;">&#40;</span>underTest<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">invoke</span><span style="color: #66cc66;">&#40;</span>nameOfMethodToMock, input<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>It's also possible to do the same thing without having to specify the method name using an overridden version of when:</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>PrivatePartialMockingExample.<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> PrivatePartialMockingExampleTest <span style="color: #66cc66;">&#123;</span>
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> demoPrivateMethodMocking<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;">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> expected = <span style="color: #ff0000;">&quot;TEST VALUE&quot;</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> input = <span style="color: #ff0000;">&quot;input&quot;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">/*
         * We get the method to mock by specifying the class where the
         * method is defined as well as its parameter types.
         */</span>
        <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a> methodToMock = method<span style="color: #66cc66;">&#40;</span>PrivatePartialMockingExample.<span style="color: #000000; font-weight: bold;">class</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>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        PrivatePartialMockingExample underTest = spy<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PrivatePartialMockingExample<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Notice how we pass the actual method instead of the name</span>
        when<span style="color: #66cc66;">&#40;</span>underTest, methodToMock<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">withArguments</span><span style="color: #66cc66;">&#40;</span>input<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span>expected<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        assertEquals<span style="color: #66cc66;">&#40;</span>expected, underTest.<span style="color: #006600;">methodToTest</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Optionally verify that the private method was actually called</span>
        verifyPrivate<span style="color: #66cc66;">&#40;</span>underTest<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">invoke</span><span style="color: #66cc66;">&#40;</span>methodToMock<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">withArguments</span><span style="color: #66cc66;">&#40;</span>input<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This approach allows for more a refactor friendly code since you can change the method name of the private method without having to change your test.</p>
<h3>Example #3 - Mock construction of new objects</h3>
<p>Sometimes it might be good to mock construction of new objects. Consider the following example:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> DirectoryStructure <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> create<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> directoryPath<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a> directory = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a><span style="color: #66cc66;">&#40;</span>directoryPath<span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>directory.<span style="color: #006600;">exists</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>
			<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%3AIllegalArgumentException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalArgumentException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> + directoryPath + <span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span> already exists.&quot;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> directory.<span style="color: #006600;">mkdirs</span><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>
<p>To test the create method in isolation from the file system we'd like to mock the construction of the new File instance in order to specify our expectations. To do this in PowerMock you need to prepare the class that <em>creates</em> the new object (since we don't want the new object to be created in our test, we'd like to return a mock object instead). Thus we prepare <code>DirectoryStructure.class</code> instead of <code>File.class</code>. The test may look like this when we expect that the directory doesn't exists:</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>DirectoryStructure.<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> DirectoryStructureTest <span style="color: #66cc66;">&#123;</span>
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> createDirectoryStructureWhenPathDoesntExist<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;">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> directoryPath = <span style="color: #ff0000;">&quot;mocked path&quot;</span>;
&nbsp;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a> directoryMock = mock<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// This is how you tell PowerMockito to mock construction of a new File.</span>
        whenNew<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">withArguments</span><span style="color: #66cc66;">&#40;</span>directoryPath<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span>directoryMock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Standard expectations</span>
        when<span style="color: #66cc66;">&#40;</span>directoryMock.<span style="color: #006600;">exists</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">false</span><span style="color: #66cc66;">&#41;</span>;
        when<span style="color: #66cc66;">&#40;</span>directoryMock.<span style="color: #006600;">mkdirs</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        assertTrue<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> NewFileExample<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">createDirectoryStructure</span><span style="color: #66cc66;">&#40;</span>directoryPath<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Optionally verify that a new File was &quot;created&quot;.</span>
        verifyNew<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">withArguments</span><span style="color: #66cc66;">&#40;</span>directoryPath<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<h3>Example #4 - Modify code structure or change invocations</h3>
<p>A new noteworthy feature of the 1.3 release is the new "member modification" API. Using this API you can suppress methods, fields or constructors as well stubbing and replacing methods and fields.<br />
Below you can see some examples of how to suppress members in a class:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Suppress a constructor in class ClassWithConstructor</span>
suppress<span style="color: #66cc66;">&#40;</span>constructor<span style="color: #66cc66;">&#40;</span>ClassWithConstructor.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Suppress method &quot;myMethod&quot; in class MyClass</span>
suppress<span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>MyClass.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;myMethod&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Suppress all methods in class MyClass</span>
suppress<span style="color: #66cc66;">&#40;</span>methodsDeclaredIn<span style="color: #66cc66;">&#40;</span>MyClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Suppress field with name &quot;myField&quot; in class MyClass</span>
suppress<span style="color: #66cc66;">&#40;</span>field<span style="color: #66cc66;">&#40;</span>MyClass.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;myField&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>You can also stub methods:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">//Stub the &quot;getObject&quot; method in class SuppressMethod to always return expectedValue</span>
stub<span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>SuppressMethod.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;getObject&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>expectedValue<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>And replace method invocations:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Duck-typing of static methods</span>
replace<span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>MyClass.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;getData&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">with</span><span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>MyClass2.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;getTestData&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Replace method invocation with an invocation handler to allow for proxy-based AOP</span>
replace<span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>MyClass.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;getData&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">with</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MyInvocationHandler<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>All methods can be statically imported from <code>org.powermock.api.support.membermodification.MemberModifier</code> and <code>org.powermock.api.support.membermodification.MemberMatcher</code>. For real examples refer to <a href="http://code.google.com/p/powermock/source/browse/trunk/modules/module-test/powermockito/junit4/src/test/java/samples/powermockito/junit4/membermodification/MemberModificationExampleTest.java">MemberModificationExampleTest.java</a> in subversion. </p>
<p>Note that this also works for the EasyMock extension API.</p>
<h3>Round up</h3>
<p>We've just seen some examples of how to use PowerMock's extension API for Mockito to allow to mock things normally not possible. For more information please visit our web page at <a href="http://www.powermock.org">www.powermock.org</a>.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/ie8mpa_AmnQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/10/28/untestable-code-with-mockito-and-powermock/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/10/28/untestable-code-with-mockito-and-powermock/</feedburner:origLink></item>
		<item>
		<title>The Power of Unit Testing</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/w8MIM-A3IOo/</link>
		<comments>http://blog.jayway.com/2009/05/21/the-power-of-unit-testing/#comments</comments>
		<pubDate>Thu, 21 May 2009 14:07:00 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scrum]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1761</guid>
		<description><![CDATA[The purpose of Unit Testing is to verify for the developer that a software unit does what it is supposed to and is fit for use. The confidence that the developer gets, gives the developer courage to do other useful practices like Refactoring. Unit testing is often used to test complex units with one or [...]]]></description>
			<content:encoded><![CDATA[<p>The purpose of <a href="http://en.wikipedia.org/wiki/Unit_testing" title="Unit testing - Wikipedia, the free encyclopedia">Unit Testing</a> is to verify for the developer that a software unit does what it is supposed to and is fit for use. The confidence that the developer gets, gives the developer courage to do other useful practices like <a href="http://en.wikipedia.org/wiki/Refactoring" title="Code refactoring - Wikipedia, the free encyclopedia">Refactoring</a>. </p>
<p>Unit testing is often used to test complex units with one or more collaborators, usually with the help of mock objects. But the greatest value with unit testing, in my opinion, lies in testing the lowest level utility methods; the building blocks that simply <em>have</em> to be bullet-proof in order for the rest of the system to have a stable foundation.</p>
<p>Let's say that we have an Article domain object, storing article numbers from the database in the form "01234567":</p>
<pre>
public class Article {

    /**
     * 8 character numeric article number, eg &quot;01234567&quot;.
     */
    private String articleNumber = &quot;&quot;;

    public String getArticleNumber() {
        return articleNumber;
    }

    public void setArticleNumber(String articleNumber) {
        this.articleNumber = articleNumber;
    }
}
</pre>
<p>Business now demands that the article number should be formatted with dots here and there. They have added the story "User should see article numbers formatted as 123.456.78" to the Sprint Backlog.</p>
<p>We decide to write a test for this:</p>
<pre>
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class ArticleTest {

    @Test
    public void testGetFormattedArticleNumberNoZeros() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;98765432&quot;);
        assertEquals(&quot;987.654.32&quot;, tested.getFormattedArticleNumber());
    }
}
</pre>
<p>We search around for a while, and find several nice tools for <em>parsing</em> formatted strings, but nothing useful for <em>writing</em> formatted strings that will help us in our scenario. Lacking ideas, we desperately try <a href="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html" title="DecimalFormat (Java Platform SE 6)">DecimalFormat</a>. It's actually not that bad. If we divide by 100, we'll automatically get the right-most dot, don't we? We decide to give it a try:</p>
<pre>
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;

public class Article {

    /**
     * 8 character numeric article number, eg &quot;01234567&quot;.
     */
    private String articleNumber = &quot;&quot;;

    public String getArticleNumber() {
        return articleNumber;
    }

    public void setArticleNumber(String articleNumber) {
        this.articleNumber = articleNumber;
    }

    /**
     * Retrieves the formatted article number.
     *
     * TODO I didn&#x27;t find a nice generic formatting method, so I wrote this terrible hack.
     *
     * @return the formatted article number, eg 123.456.78
     */
    public String getFormattedArticleNumber() {
        NumberFormat nf = NumberFormat.getNumberInstance();
        DecimalFormat df = (DecimalFormat) nf;
        BigDecimal number = new BigDecimal(articleNumber);
        number = number.divide(new BigDecimal(100));
        String str = df.format(number);
        return str;
    }
}
</pre>
<p>We get a failure:</p>
<pre>expected:&lt;987[.654.]32&gt; but was:&lt;987[&nbsp;654,]32&gt;
</pre>
<p>The decimal point is a comma (,) in the default locale, and the grouping separator is a blank. We can tweak that by calling the <code>getDecimalFormatSymbols</code> method, giving us a <a href="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormatSymbols.html" title="DecimalFormatSymbols (Java Platform SE 6)">DecimalFormatSymbols</a> that we can change:</p>
<pre>DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
symbols.setDecimalSeparator(&#x27;.&#x27;);
symbols.setGroupingSeparator(&#x27;.&#x27;);
df.setDecimalFormatSymbols(symbols);
</pre>
<p>We also make sure the grouping size is always three by calling <code>df.setGroupingSize(3)</code>. Here is the code so far:</p>
<pre>public String getFormattedArticleNumber() {
    NumberFormat nf = NumberFormat.getNumberInstance();
    DecimalFormat df = (DecimalFormat) nf;
    df.setGroupingSize(3);
    DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
    symbols.setDecimalSeparator(&#x27;.&#x27;);
    symbols.setGroupingSeparator(&#x27;.&#x27;);
    df.setDecimalFormatSymbols(symbols);
    BigDecimal number = new BigDecimal(articleNumber);
    number = number.divide(new BigDecimal(100));
    String str = df.format(number);
    return str;
}
</pre>
<p>Success! Excellent. Now, we suspect that there might be problems with leading zeros, so we add another test:</p>
<pre>
    @Test
    public void testGetFormattedArticleNumberLeadingZero() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;01234567&quot;);
        assertEquals(&quot;012.345.67&quot;, tested.getFormattedArticleNumber());
    }
</pre>
<p>As we suspected. We get a failure:</p>
<pre>expected:&lt;[0]12.345.67&gt; but was:&lt;[]12.345.67&gt;
</pre>
<p>This can be fixed by setting the minimum integer size to 6:</p>
<pre>df.setMinimumIntegerDigits(6);
</pre>
<p>We run the test suite again. Success! Great. We suspect that <em>trailing</em> zeros can also be troublesome. We add a few tests for that:</p>
<pre>
    @Test
    public void testGetFormattedArticleNumberSingleTrailingZero() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;98765430&quot;);
        assertEquals(&quot;987.654.30&quot;, tested.getFormattedArticleNumber());
    }

    @Test
    public void testGetFormattedArticleNumberTrailingZeros() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;98765400&quot;);
        assertEquals(&quot;987.654.00&quot;, tested.getFormattedArticleNumber());
    }

    @Test
    public void testGetFormattedArticleNumberAllZeros() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;00000000&quot;);
        assertEquals(&quot;000.000.00&quot;, tested.getFormattedArticleNumber());
    }
</pre>
<p>We run the tests. The last three tests all fail, indicating that trailing zeros are lost. We fix that by setting the minimum fraction size to 2:</p>
<pre>df.setMinimumFractionDigits(2);
</pre>
<p>Success! The complete method now looks like this:</p>
<pre>/**
 * Retrieves the formatted article number.
 *
 * TODO I didn&#x27;t find a nice generic formatting method, so I wrote this terrible hack.
 *
 * @return the formatted article number, eg 123.456.78
 */
public String getFormattedArticleNumber() {
    NumberFormat nf = NumberFormat.getNumberInstance();
    DecimalFormat df = (DecimalFormat) nf;
    df.setGroupingSize(3);
    df.setMinimumIntegerDigits(6);
    df.setMinimumFractionDigits(2);
    DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
    symbols.setDecimalSeparator(&#x27;.&#x27;);
    symbols.setGroupingSeparator(&#x27;.&#x27;);
    df.setDecimalFormatSymbols(symbols);
    BigDecimal number = new BigDecimal(articleNumber);
    number = number.divide(new BigDecimal(100));
    String str = df.format(number);
    return str;
}
</pre>
<p>It's not pretty, but it works. We check in the code, relax, and think for a while. Is there a simpler way? Of course there is:</p>
<pre>/**
 * Retrieves the formatted article number.
 *
 * @return the formatted article number, eg 123.456.78
 */
public String getFormattedArticleNumber() {
    StringBuffer number = new StringBuffer(articleNumber);
    number.insert(3, &#x27;.&#x27;);
    number.insert(7, &#x27;.&#x27;);
    return number.toString();
}
</pre>
<p>Here, the power of unit testing shows. We don't even think twice about replacing the existing code. The tests still run, so we hook this code into the user interface, run the functional tests, check in, wait for a successful build, and finally ask the Product Owner to run the acceptance tests for the story.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/w8MIM-A3IOo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/21/the-power-of-unit-testing/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/05/21/the-power-of-unit-testing/</feedburner:origLink></item>
		<item>
		<title>Mocking static methods in Java system classes</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/c88yRq8nWio/</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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/c88yRq8nWio" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/</feedburner:origLink></item>
		<item>
		<title>PowerMock Part 2</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/6RtvpWc_Yzs/</link>
		<comments>http://blog.jayway.com/2009/05/01/powermock-part-2/#comments</comments>
		<pubDate>Fri, 01 May 2009 09:00:25 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2899</guid>
		<description><![CDATA[In JayView 17 we presented a short introduction to PowerMock, a framework that allows you to create automated tests for almost any code in isolation from its environment. In this article we’ll dig a bit deeper into PowerMock and explore the goals and more of its feature set. Background PowerMock is intended for developers who [...]]]></description>
			<content:encoded><![CDATA[<p><strong>In JayView 17 we presented a short introduction to PowerMock, a framework that allows you to create automated tests for almost any code in isolation from its environment. In this article we’ll dig a bit deeper into PowerMock and explore the goals and more of its feature set.</strong></p>
<h2>Background </h2>
<p>PowerMock is intended for developers who want to unit test code in isolation from its environment. The environment may be for example other classes or<br />
objects, other systems such as a database or a file-system. To isolate the unit you<br />
can use a technique called mocking. Mocks let you record and verify behavior<br />
according to your needs in order to get a deterministic behavior when executing<br />
your test, for example provide a certain return value. A similar technique is stubs<br />
that simply remove functionality and you don’t care about the return value. </p>
<h2>Why?</h2>
<p>There already exists frameworks that provide both mocks and stubs, so why<br />
create another one? First of all PowerMock is not a new framework built from<br />
scratch, instead it extends existing mock frameworks such as EasyMock and<br />
Mockito. In most cases these frameworks are still sufficient. However, there are<br />
cases when more power is needed! </p>
<p>To be able to use mock objects your code needs to be designed in a way that<br />
makes it possible to replace collaborators, for example by using the Dependency<br />
Injection pattern. Most often this is a good thing, but sometimes it leads to more<br />
complexity and a more complicated production code that is more difficult to<br />
understand. Another problem is legacy code which is seldom designed with unit<br />
testing in mind. When trying to introduce Dependency Injection you are often<br />
forced to perform a gigantic refactoring touching almost every class. Depending<br />
on how brave you are this can either be a problem or an opportunity. </p>
<p>Another common situation is when there is some initialization routine in your<br />
code or some third party library that does something that prevents you from<br />
unit testing your code. This can both be a constructor or a static initializer. For<br />
example, did you know that an interface can have a static initializer? This means<br />
that just implementing an interface can execute code beyond your control!  </p>
<h2>Goals</h2>
<p>Since there are many good mock frameworks out there already we think that<br />
instead of creating something entirely new we want to reuse the API’s that<br />
people already use and extend them with more capabilities. This means that<br />
PowerMock consists of extension APIs to other popular mock frameworks.<br />
EasyMock was the first API that we supported since we have been using it a lot.<br />
In version 1.1 we also have some basic support for Mockito and we have serious<br />
plans for a JMock extension. PowerMock is fully extendable and you can create<br />
an extension on your own as well. </p>
<p>A key goal of PowerMock is to allow you to unit test your code without having to<br />
think about the testability aspects. We would of course never encourage you to<br />
write inflexible code that is hard to maintain, but we leave the design decisions<br />
up to you and not to the technical limitations of a test or mock framework. </p>
<p>Another important goal is that PowerMock should be just another jar file. As a<br />
user you should not have to care how PowerMock does its magic. You just put it<br />
in your classpath and then you’re good to go. You don’t need to install any IDE<br />
plugin, change the JVM settings or mess with your build environment.</p>
<h2>When to use it</h2>
<h3>Using a 3rd party or legacy framework</h3>
<ul>
<li> Sometimes communication with a particular framework is done through<br />
static methods (for example Java ME). PowerMock allows you to setup<br />
expectations for these static methods and simulate the behavior you need<br />
to test.
<li> Other frameworks require you to subclass classes that contain static<br />
initializers or constructors doing something that prevents you from unit-<br />
testing your code in isolation. PowerMock allows you to remove static<br />
initializers and suppress constructors. It also allows you to mock classes<br />
inside a signed jar files even though a class is package-private.
</ul>
<h3>Design </h3>
<ul>
<li> You really want to enforce the fact that some methods are private. PowerMock allows mocking and testing of both private and final methods..
<li> You want to read or write private state from your test without adding unnecessary methods to the production code that are used only for test purposes.
<li> In some cases you want to create a new instance of an object in your production code but still be able to replace this instance with a mock object from your test.
</ul>
<h2>Examples</h2>
<p>All examples in this article are written with the EasyMock extension API.<br />
The examples are written in a way that easily demonstrates the capabilities of<br />
PowerMock and are sometimes very naive. In the examples both the code being<br />
tested and the actual test are completely pointless and is not a recommended<br />
way of coding! The reason why we use such examples is of course that code that<br />
typically need PowerMock is often quite complex and it would be hard to focus<br />
on what we are trying to demonstrate. </p>
<p>When writing tests with PowerMock you basically always need to supply<br />
two annotations at the class-level of your test as you will see in the examples<br />
below. The first is the RunWith annotation which tells JUnit to run the test<br />
with a specific JUnit runner. In PowerMock’s case you always specify the<br />
PowerMockRunner, i.e. @RunWith(PowerMockRunner.class). This is what<br />
bootstraps the entire PowerMock framework and this is how you can see that<br />
a test is using PowerMock. The PowerMockRunner initializes PowerMock’s<br />
classloader which starts to load all classes relevant for your particular test. Some<br />
of these classes need to be prepared in order to allow for testability. These are<br />
the classes that you wish to mock, for example those containing final or static<br />
methods. You supply these classes to the @PrepareForTest annotation. What<br />
PowerMock does then is to modify the byte-code of these classes at run-time so<br />
that they become testable. Let’s look at a couple of examples to clear things up. </p>
<h3>Mocking final classes or methods</h3>
<p>Imagine writing a unit test for this fictive class:</p>
<pre>
public class SomeService {
    private final SomeDao someDao;
    public SomeService(SomeDao someDao) {
        this.someDao = someDao;
    }
    public String getFormattedData() {
        String data = ”Data is missing”;
        final String actualData = someDao.getData();
        if (actualData != null) {
            data = actualData;
        }
        return data;
    }
}
</pre>
<p>For those of you who are used to unit testing it doesn’t look like any problems<br />
at first since it’s easy to inject a mock implementation of the SomeDao class to<br />
an instance of the SomeService at construction since it’s using the Dependency<br />
Injection pattern. But let’s look at the actual implementation of the SomeDao<br />
class. </p>
<pre>
public final class SomeDao extends JdbcDaoSupport {
    public final String getData() {
        /* Query a database for data,
            this is not something we want to do in a unit test */
        getJdbcTemplate().queryForObject(”some sql”, String.class);
    }
}
</pre>
<p>As you may see this class communicates with a database which is typically<br />
something we want to avoid in a unit test. The problem is that both the class<br />
and the method is final so we wouldn’t be able to mock this class with standard<br />
EasyMock. But PowerMock makes this possible using the standard EasyMock<br />
syntax: </p>
<pre>
@RunWith(PowerMockRunner.class)
@PrepareForTest(SomeDao.class)
public class SomeServiceTest {
    @Test
    public void returnedValueIsActualData() throws Exception {
        final String expectedData = ”data”;
         // We use PowerMock.createMock(..) to create
         // the mock object since it’s final.
        SomeDao someDaoMock = createMock(SomeDao.class);
        expect(someDaoMock.getState()).andReturn(expectedData);
        replayAll();
        SomeService tested = new SomeService(someDaoMock);
        final String actualData = tested.getFormattedData();
        verifyAll();
        assertEquals(expectedData, actualData);
    }
}
</pre>
<p>Looking closely you may see that we’re using the replayAll() and verifyAll()<br />
methods of the PowerMock API. These methods will replay and verify all mocks<br />
created by PowerMock so that you don’t have to keep track of them yourself.<br />
Of course PowerMock provides the standard replay(..) and verify(..) methods as<br />
well if you’d rather want to use those. </p>
<h3>Mocking and testing private methods</h3>
<p>Sometimes you may want to enforce encapsulation and use private methods.<br />
There’s a debate going on on whether one should test private methods by<br />
themselves or not but we’ll leave that decision up to you. Mocking a method<br />
of the class being tested is known as partial mocking. PowerMock lets you do<br />
partial mocking and also invoke private methods during a test. Let’s say we have<br />
the following class: </p>
<pre>
public class DataService {
    public boolean replaceData(final String dataId,
                      final byte[] binaryData) {
        // ...do something... then
        return modifyData(dataId, binaryData);
    }
    public boolean deleteData(final String dataId) {
        // ...do something else... then
        return modifyData(dataId, null);
    }
    private boolean modifyData(String dataId, byte[] binaryData) {
        // Imagine this method doing something
         // complex and expensive.
    }
}
</pre>
<p>DataService has two public methods that both calls the private modifyData<br />
method and you may want to unit test these methods. You may want to test<br />
replace replaceData without invoking modifyData or maybe just test the private<br />
method itself. PowerMock lets you do both. To mock the modifyData method<br />
you create a partial mock using PowerMock.createPartialMock(..) and to setup<br />
expectations for a private method you use the PowerMock.expectPrivate(..)<br />
method. For the replaceData method the test could look like this: </p>
<pre>@RunWith(PowerMockRunner.class)
@PrepareForTest(DataService.class)
public class DataServiceTest {
    @Test
    public void testReplaceData() throws Exception {
        final String methodName = ”modifyData”;
        final byte[] expectedBinaryData = new byte[] { 42 };
        final String expectedDataId = ”id”;
        // Mock only the modifyData method
        DataService tested =
             createPartialMock(DataService.class, methodName);
        /*
         * This is the simplest way to expect
         * a method call to a private method.
         */
        expectPrivate(tested, methodName, expectedDataId,
                expectedBinaryData).andReturn(true);
        replay(tested);
        assertTrue(tested.replaceData(expectedDataId,
                 expectedBinaryData));
        verify(tested);
    }
}</pre>
<p>PowerMock also provides utility methods located in the Whitebox class that can<br />
assist you with accessing internal state, executing private methods or constructors<br />
etc. So if we’d like to test the modifyData method instead of mocking it we can<br />
do so by using the Whitebox.invokeMethod(..) functionality: </p>
<pre>boolean success = (Boolean) Whitebox.invokeMethod(tested, ”modifyData”,
”myDataId”, new byte[]{42}); </pre>
<p>As you can see you just supply the instance containing the method, the method<br />
name itself and the arguments that you want to pass to the method. </p>
<p>Note that in general you should avoid testing and mocking private methods<br />
as these tests are often fragile and tightly coupled with the implementation.<br />
During refactoring, when you most need your test cases, you may be forced to<br />
simply throw away tests that are too tightly coupled to the old implementation.<br />
Therefore, when writing tests you should always focus on testing expected<br />
behavior and not check implementation details. </p>
<h3>Mocking new object constructions</h3>
<p>Let’s say we have a class that looks like this: </p>
<pre>
public class Directory {
    public boolean createDirectoryStructure(String directoryPath) {
        File directory = new File(directoryPath);
        if (directory.exists()) {
            throw new IllegalArgumentException(”\”” +
                directoryPath + ”\” already exists.”);
        }
        return directory.mkdirs();
    }
}
</pre>
<p>When unit testing this class we want to isolate ourselves from the file-system<br />
environment since what’s interesting for us to test whether a directory already<br />
exists or not. So what we want to do is to create a mock object of the File class<br />
and replace the file instance with this mock object. This is something that is<br />
normally not possible since we’re creating a new File instance in our code. But<br />
with PowerMock you can indeed do so: </p>
<pre>
@RunWith(PowerMockRunner.class)
@PrepareForTest( Directory.class )
public class DirectoryTest {
    @Test
    public void givenThatDirectoryDoesntExistAssertThatItIsCreated() {
        final String path = ”directoryPath”;
        File fileMock = createMock(File.class);
        expectNew(File.class, path).andReturn(fileMock);
        expect(fileMock.exists()).andReturn(false);
        expect(fileMock.mkdirs()).andReturn(true);
        replayAll();
        Directory tested = new Directory();
        assertTrue(tested.createDirectoryStructure(path));
        verifyAll();
    }
} </pre>
<p>As you can see we’re using the expectNew functionality of PowerMock to<br />
intercept the call to new File and return the mock object instead. Note that we<br />
prepare the Directory class for test and not the File class. The reason for this is<br />
that it is the Directory instance that creates a new File instance and thus the File<br />
class itself doesn’t have to be prepared for test. </p>
<h3>Suppressing unwanted behavior</h3>
<p>Sometimes you want to suppress a method, constructor or static initializer<br />
of your production code when executing your test because they are of no<br />
importance to the test or they even prevent you from testing your unit. Let’s<br />
take a look at the following example: </p>
<pre>public class ExampleWithBaseClass extends ThirdPartyFrameworkBaseClass {
    private final String message;
    public ExampleWithBaseClass(String message) {
        this.message = message;
    } 

    public String getMessage() {
        return message;
    }
}
</pre>
<p>This seems like an easy class to unit test (so easy in fact that you probably<br />
shouldn’t test it, but let’s do it anyway for demonstration purposes). But wait,<br />
let’s look at what the ThirdPartyFrameworkBaseClass class looks like: </p>
<pre>public class ThirdPartyFrameworkBaseClass {
    public ThirdPartyFrameworkBaseClass() {
        System.loadLibrary(”framework.dll”);
    }
} </pre>
<p>This class tries to load a dll file which may not be present when you run<br />
a unit test for the ExampleWithBaseClass class and thus will lead to<br />
an exception. With PowerMock you can just suppress the constructor<br />
of the ThirdPartyFrameworkBaseClass so that you can unit test the<br />
ExampleWithBaseClass class in isolation from the native framework dll.<br />
Sometimes this may also save you a lot of time not having to bootstrap an entire<br />
framework. You can achieve this by using the suppressConstructor method of<br />
the PowerMock API. In this case we would do: </p>
<pre>@RunWith(PowerMockRunner.class)
@PrepareForTest(ExampleWithBaseClass.class)
public class ExampleWithBaseClassTest {
    @Test
    public void assertThatConstructorMessageDoesntChange() throws
    Exception {
        // This is how we suppress the constructor
        suppressConstructor(ThirdPartyFrameworkBaseClass.class);
        final String message = ”myMessage”;
        ExampleWithBaseClass tested = new
        ExampleWithBaseClass(message);
        assertEquals(message, tested.getMessage());
    }
}
</pre>
<p>That’s it! PowerMock can also suppress static initializers, methods and fields.</p>
<h3>Access private state</h3>
<p>For mutable objects internal state may change after a method has been invoked.<br />
When unit testing such objects it’s good to have an easy way to get a hold of this<br />
state and see if it has updated accordingly. PowerMock supplies several useful<br />
reflection utilities specially designed for unit testing. All of these reflection<br />
utilities are located in the org.powermock.reflect.Whitebox class. </p>
<p>For demonstration purposes let’s say we have a class that looks like this: </p>
<pre>public class ServiceHolder {
    private final Set<Object> services = new HashSet<Object>();
    public void addService(Object service) {
        services.add(service);
    }
    public void removeService(Object service) {
        services.remove(service);
    }
}</pre>
<p>What we’re interested in testing here is that if we add a service we want to make<br />
sure that it’s added to the services set. But since the services field is private this<br />
is normally not so easy. But with PowerMock you can do like this: </p>
<pre>@Test
public void testAddService() throws Exception {
    ServiceHolder tested = new ServiceHolder();
    final Object service = new Object();
    tested.addService(service);
    // This is how you get the private
    // services set using PowerMock
    Set<String> services = (Set<String>)
        Whitebox.getInternalState(tested, Set.class);
    assertEquals(”Size of the \”services\” Set should be 1”,
        1, services.size());
    assertSame(”Services didn’t contain the expected service”,
            service, services.iterator().next());
} </pre>
<p>As you can see we’re using the Whitebox.getInternalState(..) functionality to<br />
get the services field from the ServiceHolder instance. Note that we specified<br />
the type of the field (Set.class) instead of specifying the name of the field. This<br />
makes the code more refactor friendly as the name of the field can change.<br />
You could have achieved the same result by using the not-so-refactor-friendly<br />
alternative Whitebox.getInternalState(tested, “services”). Sometimes you need<br />
to revert to this second approach anyway, for example if you have two fields of<br />
the same type in the class.</p>
<p>Once again, accessing private state will couple the test to the implementation<br />
and should in general be avoided. However, we have seen several cases where<br />
this has been necessary in order to test the code without compromising<br />
encapsulation in the production code. </p>
<h2>Summary</h2>
<p>As you’ve seen PowerMock is capable of mocking and testing many things that<br />
are normally difficult or even impossible. PowerMock gives you more design<br />
options and does not force you to do trade-offs in favour for testability. However,<br />
always design your tests carefully and avoid tight coupling between the test<br />
cases and implementation details. PowerMock have many more features than we<br />
have shown here and we also have a lot in store for the future. Please have a look<br />
at <a href="http://www.powermock.org">http://www.powermock.org</a> for more information, downloads and tutorials. </p>
<p><em>Johan Haleby<br />
Jan Kronquist</em>  </p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/6RtvpWc_Yzs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/01/powermock-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/05/01/powermock-part-2/</feedburner:origLink></item>
		<item>
		<title>Questioning “testable design”</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/FJrJ5bAjZMI/</link>
		<comments>http://blog.jayway.com/2009/04/01/questioning-testable-design/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 09:11:14 +0000</pubDate>
		<dc:creator>Mattias Ask</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[toos]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1480</guid>
		<description><![CDATA[After a discussion about PowerMock with @olabini on Twitter I felt I had to write a post on testability. The truth "Autonomous, re-runnable, code-based tests are objectivity good" has created a perceived truth, namely "Testable design is good design". This assumption is incorrect. The phrase "testable design" is dependent of two things; the design of [...]]]></description>
			<content:encoded><![CDATA[<p>After a <a href="http://search.twitter.com/search?max_id=1430211295&page=1&q=olabini+mattiasask">discussion about PowerMock</a> with <a href="http://twitter.com/olabini">@olabini</a> on Twitter I felt I had to write a post on testability.</p>
<p>The truth "<em>Autonomous, re-runnable, code-based tests are objectivity good</em>" has created a perceived truth, namely "<em>Testable design is good design</em>". This assumption is incorrect.</p>
<p>The phrase "testable design" is dependent of two things; the design of the code under test AND the tools used for testing the code. This is a problem when the major tools today in the Java world tells you to not test private methods, final classes<br />
and so on.</p>
<p>Yes, there is a big overlap between testable design and good design, but should the test tools you use govern your design? Conscious and good design choices should govern the structure of your code, and testability should come with that.</p>
<p><a href="http://code.google.com/p/powermock/">PowerMock</a> changes the phrase "Testable design is always good" to what it should be, and that is "Good design is always testable".</p>
<p>And when it comes to the hurt of legacy code, would you rather re-factor the code in order to write tests, or write tests to be able to re-factor the code safely?</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/FJrJ5bAjZMI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/04/01/questioning-testable-design/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/04/01/questioning-testable-design/</feedburner:origLink></item>
		<item>
		<title>EasyMock: Capturing arguments from multiple calls</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/oSZGpRkhhMY/</link>
		<comments>http://blog.jayway.com/2009/03/25/easymock-capturing-arguments-from-multiple-calls/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 16:07:59 +0000</pubDate>
		<dc:creator>Jens Nordahl</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1339</guid>
		<description><![CDATA[With EasyMock it is, in some cases, difficult to set up sufficiently precise expectations for the mocks. This may be because we don't know in advance with which arguments they get called or how often they get called. Or because the verification, we have to make in the test, involves relating the calls to one mock object to the calls to another mock object or relating calls to mock objects to data returned from the object being tested. 

In such cases the solution may be to capture "traces" of the method calls to the mock objects, and then, after having exercised the object being tested, to make the needed verifications using the captured traces.
]]></description>
			<content:encoded><![CDATA[<p>The EasyMock mocking framework makes it easy to use mocks in tests, to set up precise expectations to mock method calls, and to simulate return values and exceptions thrown from mock methods. </p>
<p>However, in some cases it is difficult to set up sufficiently precise expectations for the mocks</p>
<ul>
<li>because we don't know in advance with which arguments they get called or how often they get called
</li>
<li>or because the verification, we have to make in the test, involves relating the calls to one mock object to the calls to another mock object or relating calls to mock objects to data returned from the object being tested.
</li>
</ul>
<p>In such cases the solution may be to capture "traces" of the method calls to the mock objects, and then, after having exercised the object being tested, to make the needed verifications using the captured traces.</p>
<h3>Example</h3>
<p>Consider as an example a card game simulation with a <code>Dealer</code> object collaborating with multiple <code>Player</code> objects:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Dealer <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> deal<span style="color: #66cc66;">&#40;</span>Set&lt;Card&gt; deck<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> addPlayer<span style="color: #66cc66;">&#40;</span>Player player<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Player <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> addCard<span style="color: #66cc66;">&#40;</span>Card card<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>The rules for the Dealer are:</p>
<ul>
<li>Each player must get at least two, and at most six cards</li>
<li>Four cards for each player must be dealt in total </li>
<li>Cards cannot disappear, ie. after dealing, any card not given to a player must remain in the deck</li>
<li>Cards dealt to the players must be removed from the deck</li>
<li>The dealer may deal the cards randomly</li>
</ul>
<h3>Naive test</h3>
<p>Now suppose we want to test the Dealer using EasyMock to mock the Players. How can we set up the expectations to test that the Dealer follows the rules? We can expect that the Dealer will call <code>Player.addCard()</code>, but we can't assume in advance exactly how often and with which cards. We may set up expectations like this:</p>
<pre class="java">@Test
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testDealFor2Players<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
    Player player1Mock = createMock<span style="color: #66cc66;">&#40;</span>Player.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
    player1Mock.<span style="color: #006600;">addCard</span><span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#40;</span>Card<span style="color: #66cc66;">&#41;</span> anyObject<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
    expectLastCall<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">times</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    Player player2Mock = createMock<span style="color: #66cc66;">&#40;</span>Player.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
    player2Mock.<span style="color: #006600;">addCard</span><span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#40;</span>Card<span style="color: #66cc66;">&#41;</span> anyObject<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
    expectLastCall<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">times</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    replay<span style="color: #66cc66;">&#40;</span>player1Mock, player2Mock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    Dealer dealer = <span style="color: #000000; font-weight: bold;">new</span> DealerImpl<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    dealer.<span style="color: #006600;">addPlayer</span><span style="color: #66cc66;">&#40;</span>player1Mock<span style="color: #66cc66;">&#41;</span>;
    dealer.<span style="color: #006600;">addPlayer</span><span style="color: #66cc66;">&#40;</span>player2Mock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    Set&lt;Card&gt; deck = createDeck<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    dealer.<span style="color: #006600;">deal</span><span style="color: #66cc66;">&#40;</span>deck<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    verify<span style="color: #66cc66;">&#40;</span>player1Mock, player2Mock<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>With this naive test we only get to test the rule "Each player must get at least two, and at most six cards" - this is clearly not by any measure a good enough test of the Dealer. </p>
<p>In order to test the other rules, we have to somehow relate the actual calls to <code>player1Mock.addCard()</code> to the actual calls to <code>player1Mock.addCard()</code> and to the state of the <code>deck</code> after executing <code>Dealer.deal()</code>.</p>
<h3>Simple capture</h3>
<p>EasyMock has a feature called Capture which allows us to capture the arguments with which mocks are called, such that we can verify the argument values after having exercised the object being tested. It works something like this:</p>
<pre class="java">Player player1Mock = createMock<span style="color: #66cc66;">&#40;</span>Player.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
Capture&lt;Card&gt; capturedCard = <span style="color: #000000; font-weight: bold;">new</span> Capture&lt;Card&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Expect one call to addCard with any arg. Capture arg value for later</span>
player1Mock.<span style="color: #006600;">addCard</span><span style="color: #66cc66;">&#40;</span> capture<span style="color: #66cc66;">&#40;</span>capturedCard<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>; 
&nbsp;
<span style="color: #808080; font-style: italic;">// ...</span>
&nbsp;
dealer.<span style="color: #006600;">deal</span><span style="color: #66cc66;">&#40;</span>deck<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Now we can verify what we want about the captured card, eg.</span>
assertEquals<span style="color: #66cc66;">&#40;</span> Card.<span style="color: #006600;">Suit</span>.<span style="color: #006600;">SPADES</span>, capturedCard.<span style="color: #006600;">getValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getSuit</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;</pre>
<p>This seems like a step in the right direction. However, using this capture feature is hard when we have to capture multiple values from multiple calls to the mock objects, and doesn't really seem to work at all when we don't know the number of calls in advance.</p>
<h3>Capturing values from multiple calls</h3>
<p>The solution to the problem lies in writing our own EasyMock argument matcher, similar to how EasyMock implements capture internally, but extended so it can accept multiple argument values for multiple methods calls: </p>
<ul>
<li>Create a class <code>MultiCaptureMatcher</code> implementing <code>org.easymock.IArgumentMatcher</code>. The class has a collection  instance variable to collect the argument values. EasyMock delegates to an instance of this class whenever the corresponding mock object method gets called.</li>
<li>Create a static method to be used when setting up expectations - this static method creates an instance of the <code>MultiCaptureMatcher</code> and tells EasyMock to use that matcher for the correponding expected method call.</li>
</ul>
<p>Here is the code:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MultiCaptureMatcher&lt;T&gt; <span style="color: #000000; font-weight: bold;">implements</span> IArgumentMatcher <span style="color: #66cc66;">&#123;</span>
&nbsp;
    Collection&lt;T&gt; captureDestination;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> MultiCaptureMatcher<span style="color: #66cc66;">&#40;</span>Collection&lt;T&gt; captureDestination<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;">captureDestination</span> = captureDestination;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> appendTo<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a> buffer<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        buffer.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;multiCapture(&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span>captureDestination.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;)&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> matches<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> actual<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        captureDestination.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>T<span style="color: #66cc66;">&#41;</span> actual<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">true</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> &lt;S&gt; S multiCapture<span style="color: #66cc66;">&#40;</span>Collection&lt;S&gt; destination<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      reportMatcher<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MultiCaptureMatcher&lt;S&gt;<span style="color: #66cc66;">&#40;</span>destination<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">null</span>;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>With this argument matcher we can now set up "expectations" like this:</p>
<pre class="java">Player player1Mock = createMock<span style="color: #66cc66;">&#40;</span>Player.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
Set&lt;Card&gt; player1Cards = <span style="color: #000000; font-weight: bold;">new</span> HashSet&lt;Card&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
player1Mock.<span style="color: #006600;">addCard</span><span style="color: #66cc66;">&#40;</span> MultiCaptureMatcher.<span style="color: #006600;">multiCapture</span><span style="color: #66cc66;">&#40;</span>player1Cards<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
expectLastCall<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">anyTimes</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>I put "expectations" in quotation marks because it is not really an expectation in any real sense, but rather tells EasyMock, that the addCard method may get called any number of times with any arguments - EasyMock shouldn't do any verification, but just capture the arguments for later manual verification. </p>
<p>Here the <code>player1Cards</code> set acts as a destination for captured values. Every time during the test that <code>player1Mock.addCard()</code> gets called, the argument gets added to the <code>player1Cards</code> set. </p>
<p>After the Dealer has been tested, we can then use the captured values in player1Cards to whatever verifications we may want.</p>
<p>Here is a complete example using <code>MultiCaptureMatcher</code> to test all of the Dealer rules:</p>
<pre class="java">@Test
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testDealFor2Players<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
    Player player1Mock = createMock<span style="color: #66cc66;">&#40;</span>Player.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
    Set&lt;Card&gt; player1Cards = <span style="color: #000000; font-weight: bold;">new</span> HashSet&lt;Card&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    player1Mock.<span style="color: #006600;">addCard</span><span style="color: #66cc66;">&#40;</span> MultiCaptureMatcher.<span style="color: #006600;">multiCapture</span><span style="color: #66cc66;">&#40;</span>player1Cards<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
    expectLastCall<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">anyTimes</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    Player player2Mock = createMock<span style="color: #66cc66;">&#40;</span>Player.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
    Set&lt;Card&gt; player2Cards = <span style="color: #000000; font-weight: bold;">new</span> HashSet&lt;Card&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    player2Mock.<span style="color: #006600;">addCard</span><span style="color: #66cc66;">&#40;</span> MultiCaptureMatcher.<span style="color: #006600;">multiCapture</span><span style="color: #66cc66;">&#40;</span>player2Cards<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
    expectLastCall<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">anyTimes</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    replay<span style="color: #66cc66;">&#40;</span>player1Mock, player2Mock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    Dealer dealer = <span style="color: #000000; font-weight: bold;">new</span> DealerImpl<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    dealer.<span style="color: #006600;">addPlayer</span><span style="color: #66cc66;">&#40;</span>player1Mock<span style="color: #66cc66;">&#41;</span>;
    dealer.<span style="color: #006600;">addPlayer</span><span style="color: #66cc66;">&#40;</span>player2Mock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    Set&lt;Card&gt; deck = createDeck<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #808080; font-style: italic;">// Store original deck for later comparison</span>
    Set&lt;Card&gt; originalDeck = <span style="color: #000000; font-weight: bold;">new</span> HashSet&lt;Card&gt;<span style="color: #66cc66;">&#40;</span>deck<span style="color: #66cc66;">&#41;</span>;
    dealer.<span style="color: #006600;">deal</span><span style="color: #66cc66;">&#40;</span>deck<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    verify<span style="color: #66cc66;">&#40;</span>player1Mock, player2Mock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// Each player must have been dealt 2 to 6 cards</span>
    assertTrue<span style="color: #66cc66;">&#40;</span>player1Cards.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>&gt;=<span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>;
    assertTrue<span style="color: #66cc66;">&#40;</span>player1Cards.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>&lt;=<span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#41;</span>;
    assertTrue<span style="color: #66cc66;">&#40;</span>player2Cards.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>&gt;=<span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>;
    assertTrue<span style="color: #66cc66;">&#40;</span>player2Cards.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>&lt;=<span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// For two players 8 cards must have been dealt</span>
    assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">8</span>, player1Cards.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>+player2Cards.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// Check that no cards have disappeared, and that any card is either in</span>
    <span style="color: #808080; font-style: italic;">// the deck or belongs to one but not both players</span>
    assertEquals<span style="color: #66cc66;">&#40;</span>originalDeck.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, deck.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>+player1Cards.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>+player2Cards.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    assertEquals<span style="color: #66cc66;">&#40;</span>originalDeck, SetUtils.<span style="color: #006600;">union</span><span style="color: #66cc66;">&#40;</span>deck, player1Cards, player2Cards<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<h3>Caveat</h3>
<p>There is one catch to be aware of with this approach: When an argument object is captured, we capture a reference to the object - not a copy of the objects state. This means that if argument objects get modified after being captured, for example because the object being tested modifies the argument objects after calling the mocks, then the verification of captured objects will see the modified object state instead of the object state at the time of capture.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/oSZGpRkhhMY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/25/easymock-capturing-arguments-from-multiple-calls/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/03/25/easymock-capturing-arguments-from-multiple-calls/</feedburner:origLink></item>
		<item>
		<title>Getting started with JavaME jUnit testing</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/A4EAx9IhIeA/</link>
		<comments>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 14:36:36 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1191</guid>
		<description><![CDATA[Introduction Unit testing is a very powerful tool that should be included in every developer's toolbox. Unfortunately, this has not always been the case, especially not among MIDlet developers. One reason is that JavaME projects usually are small (compared to Java SE projects), which implies that manual testing could be enough. However, as soon as [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Unit testing is a very powerful tool that should be included in every developer's toolbox. Unfortunately, this has not always been the case, especially not among MIDlet developers. One reason is that JavaME projects usually are small (compared to Java SE projects), which implies that manual testing could be enough. However, as soon as you start developing production code you really should consider to automate your tests by developing your own test suite. </p>
<p>Some of you may have played around with <a href="http://sourceforge.net/projects/jmunit">JMUnit</a> project. It is a nice framework that allows you to write tests that can be transferred to your phone or emulator and you will see the test result on the display. Alternatively, the tests can be executed by Ant. Still, there are some limitations that you cannot bypass:</p>
<ul>
<li>Because of CLDC's lack of reflection, you cannot benefit from the powers of <a href="http://www.junit.org/">jUnit 4.x</a>.</li>
<li>You cannot create mock objects. This means that if a class has dependencies to other classes you will perform an integration test rather than a <i>unit</i> test.</li>
<li>The turn around time for test, debug and retest, is significantly larger compared to Java SE unit testing, especially if you are executing the test on the phone.</li>
</ul>
<p>No offence to the JMUnit guys, they are restricted by the limitations of the CLDC VM and the fact that you need a target device (a phone or an emulator) to run the tests on. But maybe there is a workaround to solve these problems? With some tricks, it is possible to unit test your JavaME code in the same way as you would unit test your Java SE code. In other words, you can execute the tests <i>on the PC side without deploying the tests to an emulator or a phone</i>. </p>
<h3>PowerMock</h3>
<p>One part of the solution is to mock any platform dependencies. Previously, it was an awkward job to do, but the introduction of  <a href="http://code.google.com/p/powermock/">PowerMock</a> allows us to mock the many static methods in MIDP and CLDC. The easiest way to get started with powermock is to download the <a href="http://code.google.com/p/powermock/downloads/list">powermock-1.2-with-dependencies.zip</a>. In another <a href="http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/">post</a> I have explained how PowerMock can be used to mock the RecordStore in MIDP.</p>
<h3>Project configuration</h3>
<p>If you are using Eclipse, you need two projects, one for your phone application and the other your test code. This is because different projects can have different java compiler settings.</p>
<ul>
<li>Create a <i>MIDlet</i> project. This is your phone application. Make sure that the "Java Compiler" compliance level is "1.3".</li>
<li>Create a <i>Java</i> project. This is the test project where you will write your tests. Make sure that the "Java Compiler" compliance level is set to "1.6" (or to whatever JDK version you have installed).
<ul>
<li>Add the midlet project you just created to "Required projects" in the "Java Build Path" setting.</li>
<li>Add the PowerMock jar files and their dependencies to "Libraries" in the "Java Build Path" setting.</li>
</ul>
</ul>
<p>In the MIDlet project, you write your application code and in the java test project you write your java jUnit tests. Normal package protection rules apply, so you should consider to reuse the package name from the class in the midlet project you would like to test when you are writing the test class in the java project.</p>
<h3>Automation</h3>
<p>Naturally, it is possible to automate the test by using build tools. Here is an example using of an Ant build.xml file:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="font-weight: bold; color: black;">?&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;project</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Example&quot;</span> <span style="color: #000066;">default</span>=<span style="color: #ff0000;">&quot;test&quot;</span> <span style="color: #000066;">basedir</span>=<span style="color: #ff0000;">&quot;.&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;midlet.project.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_workspace/MidletProject&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;test.project.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_workspace/MidletProjectTest&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;powermock.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_path/powermock-1.2&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;wtk.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/WTK2.5.2&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;src.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${midlet.project.home}/src&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;test.src.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${test.project.home}/src&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;bin.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;classes&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;test.bin.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;test-classes&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;test.result.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;test-result&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${wtk.home}/lib&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;include</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;*.jar&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/fileset<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/path<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;pathelement</span> <span style="color: #000066;">location</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${powermock.home}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/path<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;clean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;compile&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;javac</span> <span style="color: #000066;">srcdir</span>=<span style="color: #ff0000;">&quot;${src.dir}&quot;</span>
			<span style="color: #000066;">destdir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span>
			<span style="color: #000066;">source</span>=<span style="color: #ff0000;">&quot;1.3&quot;</span>
			<span style="color: #000066;">target</span>=<span style="color: #ff0000;">&quot;1.1&quot;</span>
			<span style="color: #000066;">classpathref</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;compile-tests&quot;</span> <span style="color: #000066;">depends</span>=<span style="color: #ff0000;">&quot;compile&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;javac</span> <span style="color: #000066;">srcdir</span>=<span style="color: #ff0000;">&quot;${test.src.dir}&quot;</span>
			<span style="color: #000066;">destdir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span>
			<span style="color: #000066;">classpathref</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test&quot;</span> <span style="color: #000066;">depends</span>=<span style="color: #ff0000;">&quot;clean, compile-tests&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;junit</span> <span style="color: #000066;">printsummary</span>=<span style="color: #ff0000;">&quot;yes&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;classpath</span> <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;classpath</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;formatter</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;plain&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;batchtest</span> <span style="color: #000066;">fork</span>=<span style="color: #ff0000;">&quot;yes&quot;</span> <span style="color: #000066;">todir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
				<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.src.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/batchtest<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/junit<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/project<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Now your project configuration is setup and you can test your MIDlet code in the same way as you would test your Java SE code. </p>
<h3>What's next?</h3>
<p>If you are a dedicated MIDlet developer you would probably like to add more build targets later on to preverify, obfuscate, sign, package and deploy your MIDlet. </p>
<p>You should also consider using a continuous integration server together with your version control system and configure it to run your test suite whenever the code has been changed. Depending on the server you choose, you may also find that it may be used to present result from static code analysis tools, code coverage, code metrics and so on.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/A4EAx9IhIeA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/</feedburner:origLink></item>
		<item>
		<title>How to mock MIDP RecordStore</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/bTjTchytdI0/</link>
		<comments>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 14:32:32 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1229</guid>
		<description><![CDATA[The challenge PowerMock is a mocking framework that claims to have almost supernatural powers. According to its documentation it is able to mock both static and private methods, final classes, and other nasty things that would be insurmountable obstacles for other mock frameworks. As a result, it has been stated that it should be able [...]]]></description>
			<content:encoded><![CDATA[<h3>The challenge</h3>
<p>PowerMock is a mocking framework that claims to have almost supernatural powers. According to its documentation it is able to mock both static and private methods, final classes, and other nasty things that would be insurmountable obstacles for other mock frameworks. As a result, it has been stated that it should be able to mock the MIDP RecordStore, but so far I have not seen a working example. I accepted the challenge.</p>
<h3>Getting started</h3>
<p>I decided that writing a unit test was the best way to get started. After all, mocking is usually used together with unit testing.<br />
In order to use RecordStore you must first open it. According to the <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/rms/RecordStore.html">javadoc of RecordStore</a>, the method to be used is: <code>public static RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary)</code>.<br />
A static method that returns an instance of the RecordStore object. Following the "Mocking static methods" guidelines on the <a href="http://code.google.com/p/powermock/">PowerMock web site</a>, it seemed to be a pretty straight forward task:</p>
<ol>
<li>Use the <code>@RunWith</code> annotation at the class-level of the test case.</li>
<li>Use the <code>@PrepareForTest</code> annotation at the class-level of the test case.</li>
<li>Use <code>PowerMock.mockStatic()</code> to mock all methods of this class.</li>
<li>Use <code>PowerMock.replay()</code> to change the class to replay mode.</li>
<li>Use <code>PowerMock.verify()</code> to change the class to verify mode.</li>
</ol>
<p>Ok, a little more complicated than my ordinary EasyMock setup, but nothing to really worry about. In my case, I also needed to create a mock object of the RecordStore class itself because of the return value of the <code>openRecordStore()</code> method. </p>
<h3>The setback</h3>
<p>To my disappointment, my test failed with an <code>ExceptionInInitializerError</code>. I studied the code thoroughly to make sure that I had followed the instructions, but I concluded that error resided elsewhere. A closer look at the failure trace revealed:<br />
<code><br />
[...]<br />
Caused by: java.lang.UnsupportedOperationException: getSlowingFactor is native<br />
at javax.microedition.rms.RecordStore.getSlowingFactor(RecordStore.java)<br />
at javax.microedition.rms.RecordStore.<clinit>(RecordStore.java:2414)<br />
[...]<br />
</code><br />
Hmm, that is strange... According to the API, there should be no <code>getSlowingFactor()</code> in RecordStore? And it seems like it is called by the class initializer? When searching for an answer it seemed like this problem occurs if you have not configured the preverifier correctly. It sort of makes sense, I am not using a preverifier at all in my project and I did not like the idea of introducing one. </p>
<h3>The solution</h3>
<p>Returning to the PowerMock documentation, I discovered instructions how to "Suppressing Unwanted Behavior", maybe this was the way forward? Soon, I found the annotation <code>@SuppressStaticInitializationFor</code>, I added it to my test case and voilÃ , I had successfully mocked the RecordStore!</p>
<h3>Reference code</h3>
<p>You can find the code needed to mock the RecordStore below. If you find it interesting, you can <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/example.zip'>download</a> a more complex example where a class that uses RecordStore for persistent storage is unit tested with aid of PowerMock.</p>
<pre class="java">&nbsp;
<span style="color: #a1a100;">import static org.easymock.EasyMock.expect;</span>
<span style="color: #a1a100;">import static org.easymock.classextension.EasyMock.createMock;</span>
<span style="color: #a1a100;">import static org.junit.Assert.assertEquals;</span>
<span style="color: #a1a100;">import javax.microedition.rms.RecordStore;</span>
<span style="color: #a1a100;">import javax.microedition.rms.RecordStoreException;</span>
&nbsp;
<span style="color: #a1a100;">import org.junit.Test;</span>
<span style="color: #a1a100;">import org.junit.runner.RunWith;</span>
<span style="color: #a1a100;">import org.powermock.api.easymock.PowerMock;</span>
<span style="color: #a1a100;">import org.powermock.core.classloader.annotations.PrepareForTest;</span>
<span style="color: #a1a100;">import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;</span>
<span style="color: #a1a100;">import org.powermock.modules.junit4.PowerMockRunner;</span>
&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>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@SuppressStaticInitializationFor<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;javax.microedition.rms.RecordStore&quot;</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> RecordStoreMockTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testCreateRecordStoreMock<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> RecordStoreException <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> recordStoreName = <span style="color: #ff0000;">&quot;record_store_name&quot;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Create mocks</span>
		PowerMock.<span style="color: #006600;">mockStatic</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
		RecordStore recordStoreMock = createMock<span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Record behavior</span>
		expect<span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #006600;">openRecordStore</span><span style="color: #66cc66;">&#40;</span>recordStoreName, <span style="color: #000000; font-weight: bold;">true</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>
				recordStoreMock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Replay behavior</span>
		PowerMock.<span style="color: #006600;">replay</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Execute test and verify result</span>
		assertEquals<span style="color: #66cc66;">&#40;</span>recordStoreMock, RecordStore.<span style="color: #006600;">openRecordStore</span><span style="color: #66cc66;">&#40;</span>recordStoreName, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		PowerMock.<span style="color: #006600;">verify</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/bTjTchytdI0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/</feedburner:origLink></item>
		<item>
		<title>Mocking Eclipse IResource.accept()</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/daoVWhhTq_M/</link>
		<comments>http://blog.jayway.com/2009/01/15/mocking-eclipse-iresourceaccept/#comments</comments>
		<pubDate>Thu, 15 Jan 2009 08:39:48 +0000</pubDate>
		<dc:creator>Tobias Södergren</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=761</guid>
		<description><![CDATA[I had a junit test situation where I wanted to mock an Eclipse IResource instance but still be able to test a call-back implementation given as parameter to the mocked IResource.accept(IResourceVisitor visit) method. By default, mocking an interface gives you "call count" and expected return values but no code is executed. In order to test the implementation of IResourceVisitor, something more had to be done. Here is how I did it.]]></description>
			<content:encoded><![CDATA[<p>I am currently involved in making the ClearCase plug-in for Eclipse, the one hosted at SourceForge, a bit better. Part of the job consists of creating unit tests to make sure that my fixes will stay fixed.</p>
<p>One interesting problem was that in some of my tests, I had to mock the <code>org.eclipse.core.resources.IResource</code> interface. Nothing too hard about that, just write the following code, using EasyMock 2.4:</p>
<pre class="java">&nbsp;
@Override
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setUp<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;">super</span>.<span style="color: #006600;">setUp</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   resource1 = createMock<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;resource1&quot;</span>, IResource.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
   resource2 = createMock<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;resource2&quot;</span>, IResource.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now to my problem. First, I will discuss what the IResource.accept(IResourceVisitor visitor) metod does:<br />
The IResource.accept(...) method traverses the directory structure under the resource. For each resource found, starting with the IResource on which accept() was called, the visitor.visit(IResource resource) method is called. If the visit(...) method returns true, the directory structure under the resource is traversed, otherwise traversing stops for that specific resource. This way parts of the directory structure under an IResource can be visited.</p>
<p>The problem I encountered was that since I have an IResource mock, there is no code for the accept() method. The mock will just register that there has been a call for accept(), but the code in the IResourceVisitor.visit(IResource resource), which I want tested, is never called.</p>
<p>What to do? There are different solutions, one example is to use an implementation of IResource, for example <code>org.eclipse.core.internal.resources.Folder</code>, and create a partially mocked object and keep the code for accept(). Not a nice solution though, my test would depend on internal code in the Eclipse project. What I did instead was to use the <code>org.easymock.EasyMock.expectLastCall().andAnswer(IAnswer answer)</code> functionality. The andAnswer() method takes an IAnswer callback implementation, like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testCollectRefreshStatus<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> CoreException <span style="color: #66cc66;">&#123;</span>
   <span style="color: #808080; font-style: italic;">// Normal mock expects</span>
   expect<span style="color: #66cc66;">&#40;</span>resource1.<span style="color: #006600;">getLocation</span><span style="color: #66cc66;">&#40;</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>iPath1<span style="color: #66cc66;">&#41;</span>;
   expect<span style="color: #66cc66;">&#40;</span>iPath1.<span style="color: #006600;">toOSString</span><span style="color: #66cc66;">&#40;</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>RESOURCE_PATH_1<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">times</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
   <span style="color: #808080; font-style: italic;">// Provide code for accept(...)</span>
   resource1.<span style="color: #006600;">accept</span><span style="color: #66cc66;">&#40;</span>isA<span style="color: #66cc66;">&#40;</span>IResourceVisitor.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
   expectLastCall<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andAnswer</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> IAnswer<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;">public</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> answer<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%3AThrowable+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Throwable</span></a> <span style="color: #66cc66;">&#123;</span> <span style="color: #808080; font-style: italic;">// 1.</span>
        IResourceVisitor visitor = <span style="color: #66cc66;">&#40;</span>IResourceVisitor<span style="color: #66cc66;">&#41;</span> EasyMock.<span style="color: #006600;">getCurrentArguments</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>; <span style="color: #808080; font-style: italic;">// 2.</span>
        visitor.<span style="color: #006600;">visit</span><span style="color: #66cc66;">&#40;</span>resource2<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// 3.</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">null</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
   expect<span style="color: #66cc66;">&#40;</span>resource2.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</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;file.txt&quot;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// 4.</span>
&nbsp;
   replayMocks<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
   <span style="color: #808080; font-style: italic;">// Perform test</span>
   myTestTarget.<span style="color: #006600;">someMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
   <span style="color: #808080; font-style: italic;">// Verify test</span>
   assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, myTestTarget.<span style="color: #006600;">getNumberOfResources</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
   verifyMocks<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Here are some comments to the marked lines in the code above:</p>
<p>1. The answer() method is dictated by the IAnswer interface.<br />
2. EasyMock provides a method to get access to the objects sent as parameters for the expected call. In this case, the call is resource1.accept(...) and the parameter is the IResourceVisitor implementation defined in myTestTarget, which is the code that should be tested.<br />
3. Here the test code has control of the call to the IResourceVisitor.visit() and a mock IResource is provided as parameter. To make the test even better, the boolean return value from the visit() call should be saved and asserted for the correct value to ensure that the intended traversing works as expected.<br />
4. Here the expectations on the mock IResource, for the visit(IResource ...) call, is defined. In this case myTestTarget calls getName() on IResource for some reason, so expectations for that is defined together with a resulting return value that would steer the logic in some direction.</p>
<p>This way the test has full control of the visitor implementation and it is fairly easy to test all the criterias that makes the IResourceVisitor.visit(...) implementation return true or false. Also, the visit() method often changes state of something else, and here it is also possible to test that the state is changed correctly by simulating multiple visit(...) calls, by adding more calls to visit at 3. in the code above. </p>
<p>/Tobias S&ouml;dergren</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/daoVWhhTq_M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/01/15/mocking-eclipse-iresourceaccept/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2009/01/15/mocking-eclipse-iresourceaccept/</feedburner:origLink></item>
		<item>
		<title>What’s new in PowerMock 1.1</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/WvxyAGFZiEU/</link>
		<comments>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 09:21:13 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[commons-logging]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[jmock]]></category>
		<category><![CDATA[log4j]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[slf4j]]></category>
		<category><![CDATA[testng]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=586</guid>
		<description><![CDATA[We're proud to announce that PowerMock 1.1 was released a couple of days ago and it has many new interesting features. Framework independence First of all the internal structure of the project has undergone major changes. PowerMock core is no longer coupled to EasyMock which means that PowerMock can now be used as a foundation [...]]]></description>
			<content:encoded><![CDATA[<p>We're proud to announce that <a href="http://www.powermock.org">PowerMock</a> 1.1 was released a couple of days ago and it has many new interesting features. </p>
<h3>Framework independence</h3>
<p>First of all the internal structure of the project has undergone major changes. PowerMock core is no longer coupled to EasyMock which means that PowerMock can now be used as a foundation for testability for other mock frameworks. Our intention is that in the future you pick a combination of a mock extension API of choice (such as EasyMock, Mockito or JMock) and a test framework of choice (such as JUnit or TestNG) to enable increased testability for your code. With the new release PowerMock has some basic support for <a href="http://www.mockito.org">Mockito</a> using the Mockito extension api. This means that you can mock final and static methods, use annotations, enable partial mocking, mocking of signed classes even if they're package private and spying of final classes and methods. Expect more features in the upcoming releases! It's possible to create your own extension API's as well so you can benefit from the PowerMock features in virtually any mock framework.</p>
<h3>Test listeners</h3>
<p>Another noteworthy feature of the new release is the test listener support. This means that you can create listeners and get notifications of various events, such as before a test method is about to execute or the outcome of an executed test method etc. The purpose of these test listeners is to provide a framework-independent way to get and react to these notifications by implementing the <code>org.powermock.core.spi.PowerMockTestListener</code> and pass it to the <code>PowerMockListener</code> annotation. PowerMock has some built-in test listeners for you to use, for example it has an <code>AnnotationEnabler</code> that let's you use annotations to create your mock objects. For example consider the following piece of code:</p>
<pre>
@RunWith(PowerMockRunner.class)
@PowerMockListener(AnnotationEnabler.class)
 public class PersonServiceTest {

 	@Mock
  	private PersonDao personDaoMock;

  	private PersonService classUnderTest;

  	@Before
  	public void setUp() {
  		classUnderTest = new PersonService(personDaoMock);
  	}
   ...
  }
</pre>
<p>Using the <code>@Mock</code> annotation eliminates the need to setup and tear-down mocks manually which minimizes repetitive test code and makes the test more readable. The <code>AnnotationEnabler</code> works for both the EasyMock and Mockito API's. You can also supply the names of the methods that you wish to mock if you want to create a partial mock, for example:</p>
<pre>
@RunWith(PowerMockRunner.class)
@PowerMockListener(AnnotationEnabler.class)
 public class PersonServiceTest {

 	@Mock("getPerson")
  	private PersonDao personDaoMock;

  	private PersonService classUnderTest;

  	@Before
  	public void setUp() {
  		classUnderTest = new PersonService(personDaoMock);
  	}
   ...
  }
</pre>
<p>This piece of code will instruct PowerMock to create a partial mock of the PersonDao where only the "getPerson" method is mocked. Since EasyMock has support for nice and strict mocks you can use the <code>@MockNice</code> and <code>@MockStrict</code> annotations to get the benefits of this.</p>
<h3>Mock policies</h3>
<p>One really cool feature of the 1.1 release is something that we refer to as mock policies. A Mock Policy can be used to make it easier to unit test some code with PowerMock in isolation from a certain framework. A mock policy implementation can for example suppress some methods, suppress static initializers or intercept method calls and change their return value (for example to return a mock object) for a certain framework or set of classes or interfaces. A mock policy can for example be implemented to avoid writing repetitive setup code for your tests. Say that you're using a framework X that in order for you to test it requires that certain methods should always return a mock implementation. Perhaps some static initializers must be suppressed as well. Instead of copying this code between tests it would be a good idea to write a reusable mock policy. </p>
<p>PowerMock 1.1 provides three mock policies out of the box for mocking slf4j, java commons-logging and log4j. Let's pick slf4j as an example and let's say you have a class that looks like this:</p>
<pre>
public class Slf4jUser {
        private static final Logger log = LoggerFactory.getLogger(Slf4jUser.class);

        public final String getMessage() {
                log.debug("getMessage!");
                return "log4j user";
        }
}
</pre>
<p>To stub all calls to the logger you can use the Slf4j mock policy that takes care of doing all necessary setup for you. You use it like this:</p>
<pre>
@RunWith(PowerMockRunner.class)
@MockPolicy(Slf4jMockPolicy.class)
public class Slf4jUserTest {
     ...
}
</pre>
<p>Note that we don't have do any setup at all to mock slf4j, the Slf4jMockPolicy takes care of this.</p>
<p>Mock policies can also be chained or nested like this:</p>
<pre>
@RunWith(PowerMockRunner.class)
@MockPolicy({MockPolicyX.class, MockPolicyY.class})
public class MyTest {
    ...
}
</pre>
<p>You can of course create your own mock policies by implementing the <code>org.powermock.core.spi.PowerMockPolicy</code> interface. For more information on mock policies please have a look at the <a href="http://code.google.com/p/powermock/wiki/MockPolicies">documentation</a>. </p>
<h3>Other</h3>
<p>There are of course many other smaller features and improvements such as the ability to suppress individual fields and better support for resetting mocks in the EasyMock API. You can read about all the new features and bug fixes in the <a href="http://powermock.googlecode.com/svn/trunk/changelog.txt">changelog</a>. Please visit our <a href="http://www.powermock.org">web-page</a> for more information and downloads.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/WvxyAGFZiEU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/</feedburner:origLink></item>
		<item>
		<title>Getting Coverage For Integration Tests</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/Q1FveJGkt8g/</link>
		<comments>http://blog.jayway.com/2008/12/13/getting-coverage-for-integration-tests/#comments</comments>
		<pubDate>Sat, 13 Dec 2008 17:59:21 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[coverage]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=565</guid>
		<description><![CDATA[Unit testing in my world is basically defined by being able to run the tests wherever and whenever; on the train, on the plane, at work, or at home. If you also have integration tests, chances are that they require some external data source or something that simply makes it impossible to run them everywhere. [...]]]></description>
			<content:encoded><![CDATA[<p>Unit testing in my world is basically defined by being able to run the tests wherever and whenever; on the train, on the plane, at work, or at home. If you also have integration tests, chances are that they require some external data source or something that simply makes it impossible to run them everywhere. If that's the case, they should probably not be included in the unit test suite.</p>
<p>Having code coverage of your unit tests is important, because it'll give you an indication of where you should focus your efforts next. The open source coverage tool <a href="http://cobertura.sourceforge.net/">Cobertura</a> gives you not only code coverage, it also shows you the <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">code complexity</a> level of packages and classes. This directs you towards the untested parts that are the most complex and most likely also the most error-prone.</p>
<h3>The Problem</h3>
<p>Rumor has it that Maven2 in an upcoming release will support having integration tests in a source folder called <code>src/it/java</code>, and run those in the integration-test phase. That would be a welcome improvement. Currently, however, Maven2 lacks good support for integration tests, and so does Cobertura. It's really a pain to get coverage on both unit tests and integration tests.</p>
<p>Let's say that you want to keep your integration tests in the same module as the unit tests. In fact, this might be a wise decision, since it's even harder to get Cobertura to provide coverage on two separate modules. Still, you do want to separate them somehow, and for now you have named the integration tests <code>IntTestSomething</code> and the unit tests <code>TestSomething</code>.</p>
<pre>
src/test/java/
`-- org
    `-- springframework
        `-- ldap
            `-- samples
                `-- article
                    |-- dao
                    |   |-- AbstractIntTestPersonDao.java
                    |   |-- IntTestPersonDaoImpl.java
                    |   `-- IntTestTraditionalPersonDaoImpl.java
                    `-- domain
                        `-- PersonTest.java
</pre>
<p>Cobertura will run the tests through Surefire, which has a <a href="http://maven.apache.org/plugins/maven-surefire-plugin/examples/inclusion-exclusion.html">default pattern</a> that picks up the unit tests, but not the integration tests. We don't want coverage on the integration tests all the time, so that's fine. But how do we include the integration tests on-demand? </p>
<h3>The Solution</h3>
<p>I will keep the unit tests in the <code>src/test/java</code> folder, but move the integration tests to a newly created <code>src/it/java</code> folder. Then I will use <a href="http://mojo.codehaus.org/build-helper-maven-plugin/">some magic</a> to incorporate that folder into the Maven build path, but only if I specify a certain profile. I will be able to do this:</p>
<pre>
% mvn test
// runs unit tests only

% mvn cobertura:cobertura
// provides coverage on unit tests only

% mvn test -Pitcov
// runs unit tests and integration tests

% mvn cobertura:cobertura -Pitcov
// provides coverage on unit tests and integration tests
</pre>
<p>Create the folder <code>src/it/java</code> and move your integration tests there. Rename them to match the Surefire default pattern, like <code>SomethingIntegrationTest</code>. That will enable Surefire to pick them up without any extra configuration.</p>
<pre>
src/it/java/
`-- org
    `-- springframework
        `-- ldap
            `-- samples
                `-- article
                    `-- dao
                        |-- AbstractPersonDaoIntegrationTest.java
                        |-- PersonDaoImplIntegrationTest.java
                        `-- TraditionalPersonDaoImplIntegrationTest.java
</pre>
<p>The unit test source folder now looks like this:</p>
<pre>
src/test/java/
`-- org
    `-- springframework
        `-- ldap
            `-- samples
                `-- article
                    `-- domain
                        `-- PersonTest.java
</pre>
<p>Now add the following profile to your Maven pom:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;profiles<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;profile<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;id<span style="font-weight: bold; color: black;">&gt;</span></span></span>itcov<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/id<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;build<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.codehaus.mojo<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>build-helper-maven-plugin<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>1.1<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;executions<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;execution<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;id<span style="font-weight: bold; color: black;">&gt;</span></span></span>add-test-source<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/id<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;phase<span style="font-weight: bold; color: black;">&gt;</span></span></span>generate-sources<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/phase<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;goals<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;goal<span style="font-weight: bold; color: black;">&gt;</span></span></span>add-test-source<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/goal<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/goals<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sources<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                          <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;source<span style="font-weight: bold; color: black;">&gt;</span></span></span>src/it/java<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/source<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/sources<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/execution<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/executions<span style="font-weight: bold; color: black;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/build<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/profile<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/profiles<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Now we're ready to run coverage:</p>
<pre>
mvn cobertura:cobertura
...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running org.springframework.ldap.samples.article.domain.PersonTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.048 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
...
</pre>
<p>Here we can see that only one test was run. The coverage report reveals that we only get coverage on the unit test of the Person domain object, giving us a total coverage of 7%:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/12/unittestsonly1-1024x642.png" alt="Coverage on unit tests only" title="Coverage on unit tests only" width="1024" height="642" class="alignnone size-large wp-image-579" /></p>
<p>We clean the target folder and run again, this time with the 'itcov' profile:</p>
<pre>
mvn clean
mvn cobertura:cobertura -Pitcov
...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImplIntegrationTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.124 sec
Running org.springframework.ldap.samples.article.dao.PersonDaoImplIntegrationTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.12 sec
Running org.springframework.ldap.samples.article.domain.PersonTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec

Results :

Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
...
</pre>
<p>This time we get both the unit tests and the integration tests, and the coverage report paints quite a different picture, with 75% coverage instead of 7%:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/12/unitanditests1-1024x642.png" alt="Coverage on unit tests and integration tests" title="Coverage on unit tests and integration tests" width="1024" height="642" class="alignnone size-large wp-image-580" /></p>
<p>What we immediately see here is that we should focus our efforts on testing our web layer. But that's another story...</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/Q1FveJGkt8g" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/13/getting-coverage-for-integration-tests/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2008/12/13/getting-coverage-for-integration-tests/</feedburner:origLink></item>
		<item>
		<title>PowerMock 1.0 released</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/gL9kaK-1HRo/</link>
		<comments>http://blog.jayway.com/2008/11/21/powermock-10-released/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 20:54:42 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[oredev]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=456</guid>
		<description><![CDATA[We have released 1.0 of PowerMock just in time for the Øredev conference! PowerMock is an open source mock framework based on EasyMock that allow you to mock static methods, private methods and even constructors. Our intent is mainly to allow unit testing of legacy code and people really seemed to appreciate this idea at the conference.]]></description>
			<content:encoded><![CDATA[<p>We have released 1.0 of <a href="http://www.powermock.org">PowerMock</a> just in time for the <a href="http://www.oredev.org/">Øredev</a> conference! PowerMock is an open source mock framework based on <a href="http://www.easymock.org/">EasyMock</a> that allow you to mock static methods, private methods and even constructors. Our intent is mainly to allow unit testing of legacy code and people really seemed to appreciate this idea at the conference.</p>
<p>We now think that the API is stable enough and we have also tested PowerMock in a couple of projects, but of course since we were presenting at the conference it is no coincidence that we released PowerMock 1.0 just days before. <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>The details of the changes can be found in the <a href="http://powermock.googlecode.com/svn/trunk/changelog.txt">changelog</a> but here are some of the highlights since <a href="http://blog.jayway.com/2008/10/27/powermock-08-released/">PowerMock 0.8</a>:</p>
<ul>
<li>The ability to <a href="http://code.google.com/p/powermock/wiki/BypassEncapsulation">set and get internal state</a> based on an object type. This means that you get more refactor friendly code while still being able to set internal state. </li>
<li>Implemented <a href="http://code.google.com/p/powermock/wiki/ReplayAllAndVerifyAll">replayAll and verifyAll</a>. These can be used to replay and verify all mocks created by PowerMock without having to explicitly specify each and everyone. Thanks to <a href="http://www.agilejava.eu/">Ivar Grimstad</a> for suggesting this!</li>
<li>Added support for specifying parameter types for expectNew. <a href="http://code.google.com/p/powermock/wiki/MockConstructor">Mocking constructor calls</a> is a unique feature of PowerMock that people typically find very cool!</li>
</ul>
<p>During the conference I talked to several people and got really good feedback. Everybody seemed to like the idea of being able to unit test legacy code and code that haven't been designed for testing. <a href="http://www.two-sdg.demon.co.uk/curbralan/kevlin.html">Kevlin Henney</a> made a good job of <a href="http://www.oredev.org/topmenu/program/tracktest/kevlinhenney.4.3efb083311ac562f9fe800011931.html">defining and describing various types of unit testing</a> during his talk at Øredev and we talked about the difference between essentially untestable code and accidentally untestable code. PowerMock solves the problem with code being untestable for technical reasons (part of the accidentally untestable). With all the great sessions and good discussions Øredev was yet again a great experience!</p>
<p>I have made <a href="http://powermock.googlecode.com/files/PowerMockAtOredev.pdf">the slides from the presentation</a> available at <a href="http://powermock.org">powermock.org</a>. Note that the demo we showed was actually from the trunk and not from the 1.0 release!</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/gL9kaK-1HRo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/21/powermock-10-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2008/11/21/powermock-10-released/</feedburner:origLink></item>
		<item>
		<title>Running Selenium RC with Firefox 3</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/JPd-a5g5P3A/</link>
		<comments>http://blog.jayway.com/2008/11/12/running-selenium-rc-with-firefox-3/#comments</comments>
		<pubDate>Wed, 12 Nov 2008 11:22:46 +0000</pubDate>
		<dc:creator>Joakim Back</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[firefox 3]]></category>
		<category><![CDATA[selenium]]></category>
		<category><![CDATA[ubuntu]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=393</guid>
		<description><![CDATA[After running into proxy errors attempting to run Selenium tests with Opera 9.62 and being unable to install Firefox 2 on Ubuntu 8.10 (unsatisfied package dependencies..) I finally ran into this gem: Hi, On windows I succeeded to run Selenium RC and Firefox 3 using the following steps 1. run firefox in profilemanager mode ("path\to\firefox.exe" [...]]]></description>
			<content:encoded><![CDATA[<p>After running into proxy errors attempting to run Selenium tests with Opera 9.62 and being unable to install Firefox 2 on Ubuntu 8.10 (unsatisfied package dependencies..) I finally ran into <a href="http://clearspace.openqa.org/message/48380#48380">this gem</a>:</p>
<p><em>Hi,</em><br />
<em><br />
On windows I succeeded to run Selenium RC and Firefox 3 using the following steps</em></p>
<p><em>1. run firefox in profilemanager mode ("path\to\firefox.exe" -profilemanager)<br />
2. create new profile (e.g. selenese) with a specific path (e.g.a directory in your workspace)<br />
3. open this new profile from within the profile manager and change the proxy settings within firefox (localhost:4444 or change accordingly in case your selenium RC server runs on a different port)<br />
4. use the following browser string within Selenium RC: *custom path\to\firefox.exe -no-remote -profile path\to\profile\selenese</em></p>
<p>I had to enable popups for the profile, but other than that.. the solution seems to work fine on ubuntu as well!</p>
<p>Edit: <a href="http://notetodogself.blogspot.com/2008/10/use-selenium-rc-in-firefox-3.html">Here's a different work-around</a>. I haven't tried it, but it does have the benefit of a generic browser path.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/JPd-a5g5P3A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/12/running-selenium-rc-with-firefox-3/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2008/11/12/running-selenium-rc-with-firefox-3/</feedburner:origLink></item>
		<item>
		<title>PowerMock 0.8 released</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/JzDxnuEHSnU/</link>
		<comments>http://blog.jayway.com/2008/10/27/powermock-08-released/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 20:37:33 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=371</guid>
		<description><![CDATA[Previously a colleague of mine described an idea for mocking static methods. Earlier this year we started an open source project to implement these ideas in a very simple to use form. The idea is that it will just be a normal jar file that extends EasyMock and JUnit. Instead of using AspectJ we have [...]]]></description>
			<content:encoded><![CDATA[<p>Previously a colleague of mine described an idea for <a href="http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/">mocking static methods</a>. Earlier this year we started an open source project to implement these ideas in a very simple to use form. The idea is that it will just be a normal jar file that extends EasyMock and JUnit. Instead of using AspectJ we have created our own classloader which means that you don't have to make changes to your build environment. <a href="http://www.powermock.org">PowerMock</a>, as the project is called,  is mostly intended for whitebox unit testing where you know what is going on inside a class or method that you want to test. There is even a class called Whitebox which can be used for simple access to private methods and fields. Besides static mocking we have many other interesting features such as mocking constructors, final classes and methods, private methods, removal of static initializers etc.</p>
<p>We have received some feedback and have also started some evaluation in one of our customer's project. Besides bug-fixes and documentation updates we are starting to stabilize the API and preparing for the 1.0 release. We are also <a href="http://www.oredev.org/topmenu/program/trackjava/johanhalebyjankronqvist.4.3efb083311ac562f9fe80009168.html">presenting PowerMock</a> at this years <a href="http://www.oredev.org/">Øredev</a> conference. You're more than welcome to try it out for yourself.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/JzDxnuEHSnU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/27/powermock-08-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2008/10/27/powermock-08-released/</feedburner:origLink></item>
		<item>
		<title>Testing Among the Clouds, Part 2</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/W1_r98M6JHc/</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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/W1_r98M6JHc" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/</feedburner:origLink></item>
		<item>
		<title>Testing Among the Clouds</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/testing/~3/N_HVG42apEw/</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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/testing/~4/N_HVG42apEw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/</feedburner:origLink></item>
	</channel>
</rss>
