<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jayway Team Blog &#187; Johan Haleby</title>
	<atom:link href="http://blog.jayway.com/author/johanhaleby/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to really fix the too many open files problem for Tomcat in Ubuntu</title>
		<link>http://blog.jayway.com/2012/02/11/how-to-really-fix-the-too-many-open-files-problem-for-tomcat-in-ubuntu/</link>
		<comments>http://blog.jayway.com/2012/02/11/how-to-really-fix-the-too-many-open-files-problem-for-tomcat-in-ubuntu/#comments</comments>
		<pubDate>Sat, 11 Feb 2012 10:31:17 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[devops]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11989</guid>
		<description><![CDATA[A couple of days ago we ran into the infamous "too many open files" when our Tomcat web server was under load. There are several blogs around the internet that tries to deal with this issue but none of them seemed to do the trick for us. Usually what you do is to set the [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of days ago we ran into the infamous "too many open files" when our Tomcat web server was under load. There are several blogs around the internet that tries to deal with this issue but none of them seemed to do the trick for us. Usually what you do is to set the ulimit to a greater value (it's something like 1024 by default). But in order to make it permanent after reboot the first thing suggested is to update the <code>/proc/sys/fs/file-max</code> file and set it to a greater value and then edit <code>/etc/security/limits.conf</code> and add the following line <code>* - nofile 2048</code> (see <a href="http://tech-torch.blogspot.com/2009/07/linux-ubuntu-tomcat-too-many-open-files.html">here</a> for more details). But none of this worked for us. We saw that when doing </p>
<pre>
cat /proc/<tomcat pid>/limits
</pre>
<p>the limit was still set to the initial value of 1024:</p>
<pre>
Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
Max resident set          unlimited            unlimited            bytes
Max processes             63810                63810                processes
<b>Max open files                1024                     1024                    files</b>
Max locked memory         65536                65536                bytes
Max address space         unlimited            unlimited            bytes
Max file locks            unlimited            unlimited            locks
Max pending signals       63810                63810                signals
Max msgqueue size         819200               819200               bytes
Max nice priority         0                    0
Max realtime priority     0                    0
Max realtime timeout      unlimited            unlimited            us
</pre>
<p>It was not until we found <a href="http://ubuntuforums.org/showthread.php?t=1583041">this</a> thread that the reason and solution became clear. Our Tomcat instance was started as a service during boot and there's a <a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=302079">bug</a> discovered and filed (with patch) in 2005 that doesn't seem to have been resolved yet. The bug reveals itself by ignoring the max number of open files limit when starting daemons in Ubuntu/Debain. So the work-around suggested by "BOK" was to edit <code>/etc/init.d/tomcat</code> and add:</p>
<pre>
ulimit -Hn 16384
ulimit -Sn 16384
</pre>
<p>Finally the max number of open files for Tomcat was increased!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/02/11/how-to-really-fix-the-too-many-open-files-problem-for-tomcat-in-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Parsing of Complex JSON and XML Documents in Java</title>
		<link>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/</link>
		<comments>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/#comments</comments>
		<pubDate>Sun, 09 Oct 2011 15:12:15 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9743</guid>
		<description><![CDATA[In this blog I'm going to demonstrate how to parse and validate more complex JSON and XML documents in Java using the REST Assured framework and the XmlPath and JsonPath components available in this framework. Since REST Assured is implemented in Groovy it can be really beneficial to take advantage of Groovy's collection API. Let's [...]]]></description>
			<content:encoded><![CDATA[<p>In this blog I'm going to demonstrate how to parse and validate more complex JSON and XML documents in Java using the <a href="http://code.google.com/p/rest-assured/">REST Assured</a> framework and the <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/xml/XmlPath.html">XmlPath</a> and <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> components available in this framework. Since REST Assured is implemented in Groovy it can be really beneficial to take advantage of Groovy's <a href="http://groovy.codehaus.org/Collections">collection</a> API. Let's begin by looking at an example in Groovy:</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> wordsWithSizeGreaterThanFour = words.<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20findAll"><span style="color: #663399;">findAll</span></a> <span style="color: #66cc66;">&#123;</span> it.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &gt; <span style="color: #cc66cc;">4</span> <span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>At the first line we simply define a list with some words but the second line is more interesting. Here we search the <code>words</code> list for all words that are longer than 4 characters by calling the <code>findAll</code> with a <a href="http://groovy.codehaus.org/Closures">Groovy closure</a>. The closure has an implicit variable called "it" which represents the current item in the list. The result is a new list, <code>wordsWithSizeGreaterThanFour</code>, containing <code>buffalo</code> and <code>dinosaur</code>. Pretty nice and simple! There are other interesting methods that we can use on collections in Groovy as well, e.g.</p>
<ul>
<li>find - finds the first item matching a closure predicate</li>
<li>collect - collect the return value of calling a closure on each item in a collection</li>
<li>sum - Sum all the items in the collection</li>
<li>max/min - returns the max/min values of the collection</li>
</ul>
<p>So how do we take advantage of this when validating our XML or JSON responses with REST Assured?</p>
<h2>XML Example</h2>
<p>Let's say we have a resource at "localhost:8080/shopping" that returns the following XML:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;shopping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;groceries&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Chocolate<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Coffee<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;supplies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Paper<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item</span> <span style="color: #000066;">quantity</span>=<span style="color: #ff0000;">&quot;4&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>Pens<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;present&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item</span> <span style="color: #000066;">when</span>=<span style="color: #ff0000;">&quot;Aug 10&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>Kathryn's Birthday<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/shopping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Let's also say we want to write a test that verifies that the category of type <code>groceries</code> has items Chocolate and Coffee. In REST Assured it can look like this:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;</pre>
</pre>
<p>What's going on here? First of all the XML path "shopping.category" returns a list of all categories. On this list we invoke a function, <code>find</code>, to return the single category that has the XML attribute, <code>type</code>, equal to "groceries". On this category we then continue by getting all the items associated with this category. Since there are more than one item associated with the groceries category a list will be returned and we verify this list against the hasItems <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> matcher. </p>
<p>But what if you want to get the items and not validate them against a Hamcrest matcher? This is also simple using the <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/xml/XmlPath.html">XmlPath</a> class:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</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> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// And get the grocieries from the response. &quot;from&quot; is statically imported from the XmlPath class</span>
List&lt;String&gt; groceries = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getList</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>If the list of groceries is the only thing you care about in the response body you can also use a shortcut:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</span>
List&lt;String&gt; groceries = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">path</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>Depth-first search</h3>
<p>It's actually possible to simplify the previous example even further:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'groceries' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p><code>**</code> is a shortcut for doing depth first searching in the XML document. We search for the first node that has an attribute named <code>type</code> equal to "groceries". Notice also that we don't end the XML path with "item". The reason is that <code>toString()</code> is called automatically on the category node which returns a list of the item values.</p>
<h3>Root path</h3>
<p>Let's expand the example by also validating that the category of type supplies contains Paper and Pens:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'groceries' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'supplies' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Paper&quot;</span>, <span style="color: #ff0000;">&quot;Pens&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Even though this works you can probably see that the XML path is almost duplicated for the two body expectations and this is of course something we want to avoid. To address this we can use a root path and path arguments:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">rootPath</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == '%s' }&quot;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span>, withArgs<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;groceries&quot;</span><span style="color: #66cc66;">&#41;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span>, withArgs<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;supplies&quot;</span><span style="color: #66cc66;">&#41;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Paper&quot;</span>, <span style="color: #ff0000;">&quot;Pens&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>By specifiying a "root path" we don't need to duplicate the entire path just to change the category type.</p>
<h2>JSON Example</h2>
<p>Let's say we have a resource at "/store" that returns the following JSON document:</p>
<pre>&nbsp;
{ &quot;store&quot; : {
  &quot;book&quot; : [
          { &quot;author&quot; : &quot;Nigel Rees&quot;,
            &quot;category&quot; : &quot;reference&quot;,
            &quot;price&quot; : 8.95,
            &quot;title&quot; : &quot;Sayings of the Century&quot;
          },
          { &quot;author&quot; : &quot;Evelyn Waugh&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;price&quot; : 12.99,
            &quot;title&quot; : &quot;Sword of Honour&quot;
          },
          { &quot;author&quot; : &quot;Herman Melville&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;isbn&quot; : &quot;0-553-21311-3&quot;,
            &quot;price&quot; : 8.99,
            &quot;title&quot; : &quot;Moby Dick&quot;
          },
          { &quot;author&quot; : &quot;J. R. R. Tolkien&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;isbn&quot; : &quot;0-395-19395-8&quot;,
            &quot;price&quot; : 22.99,
            &quot;title&quot; : &quot;The Lord of the Rings&quot;
          }
        ]
   }
}
&nbsp;</pre>
<h3>Example 1</h3>
<p>As a first example let's say we want to make the request to "/store" and assert that the titles of the books with a price less than 10 are "Sayings of the Century" and "Moby Dick":</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.findAll { it.price &lt; 10 }.title&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Sayings of the Century&quot;</span>, <span style="color: #ff0000;">&quot;Moby Dick&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Just as in the XML examples above we use a closure to find all books with a price less than 10 and then return the titles of all the books. We then use the <code>hasItems</code> matcher to assert that the titles are the ones we expect. Using <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> we can return the titles instead:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</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> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// And get all books with price &lt; 10 from the response. &quot;from&quot; is statically imported from the JsonPath class</span>
List&lt;String&gt; bookTitles = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getList</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.findAll { it.price &lt; 10 }.title&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>Example 2</h3>
<p>Let's consider instead that we want to assert that the sum of the length of all author names are greater than 50. This is a rather complex question to answer and it really shows the strength of closures and Groovy collections. In REST Assured it looks like this:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author.collect { it.length() }.sum()&quot;</span>, greaterThan<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>First we get all the authors ("store.book.author") and invoke the <code>collect</code> method on the resulting list with the closure <code>{ it.length() }</code>. What it does is to call the <code>length()</code> method on each author in the list and returns the result to a new list. On this list we simply call the <code>sum()</code> method to sum all the length's. The end result is <code>53</code> and we assert that it's greater than 50 by using the <code>greaterThan</code> matcher. But it's actually possible to simplify this even further. Consider the <code>words</code> example from the beginning of the article again:</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
&nbsp;</pre>
<p>Groovy has a very handy way of calling a function for each element in the list by using the <code>*</code> notation, e.g.</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20assert"><span style="color: #000000; font-weight: bold;">assert</span></a> <span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">8</span><span style="color: #66cc66;">&#93;</span> == words*.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>I.e. Groovy returns a new list with the lengths of the items in the words list. We can utilize this for the author list in REST Assured as well:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author*.length().sum()&quot;</span>, greaterThan<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>And of course we can use <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> to actually return the result:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as an input stream</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInputStream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">InputStream</span></a> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asInputStream</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Get the sum of all author length's as an int. &quot;from&quot; is again statically imported from the JsonPath class</span>
<span style="color: #993333;">int</span> sumOfAllAuthorLengths = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getInt</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author*.length().sum()&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// We can also assert that the sum is equal to 53 as expected.</span>
assertThat<span style="color: #66cc66;">&#40;</span>sumOfAllAuthorLengths, is<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">53</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Summary</h2>
<p>At a first glance the syntax may seem quite strange and complex but once you get used to it it's extremely powerful and actually quite simple. It's also a good place to start if you work with Java and want to understand the benefit of closures. There are a lot more features that can help you parsing and validating JSON and XML using <a href="http://code.google.com/p/rest-assured/">REST Assured</a> than the ones shown in this article. For further reading refer to the <a href="http://code.google.com/p/rest-assured/">REST Assured web-page</a> and read up on <a href="http://groovy.codehaus.org/Collections">Groovy collections</a>. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multipart Form Data File Uploading Made Simple with REST Assured</title>
		<link>http://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/</link>
		<comments>http://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 16:59:53 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9349</guid>
		<description><![CDATA[From a client perspective it has always seemed to me that uploading a large file or stream to a server using multi-part form data encoding in Java is overly complex. To address this I implemented support for it in REST Assured 1.3. Example Let's say you have a simple HTML page that performs file-uploading from [...]]]></description>
			<content:encoded><![CDATA[<p>From a client perspective it has always seemed to me that uploading a large file or stream to a server using <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2">multi-part form data encoding</a> in Java is overly complex. To address this I implemented support for it in <a href="http://code.google.com/p/rest-assured/">REST Assured</a> 1.3.</p>
<h2>Example</h2>
<p>Let's say you have a simple HTML page that performs file-uploading from a browser like this:</p>
<pre>
&lt;html&gt;
&lt;body&gt;
	&lt;form id=&quot;upload&quot; action=&quot;/fileUpload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
		&lt;input type=&quot;file&quot; name=&quot;file&quot; size=&quot;40&quot;&gt;
		&lt;input type=submit value=&quot;Upload!&quot;&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>We also assume that we have a server that receives the file and return a JSON response like this if everything was ok:</p>
<pre class="javascript">&nbsp;
<span style="color: #66cc66;">&#123;</span> <span style="color: #3366CC;">&quot;fileUploadResult&quot;</span> : <span style="color: #3366CC;">&quot;OK&quot;</span> <span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now let's use REST Assured to upload a file and assert that the upload was OK:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><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><span style="color: #ff0000;">&quot;/home/johan/some_large_file.bin&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;fileUploadResult&quot;</span>, is<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;OK&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">post</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/fileUpload&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>With so little code you've now managed to POST a large file using multi-part form data encoding to the server and asserted that the expected JSON bundled in the response body was correct.</p>
<p>But how can this work? We haven't even specified a <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.2">control name</a>? Well if you don't define a control name specifically REST Assured will default to "file". In many cases this is of course not the case. For example let's say we change the control name in the HTML form to "file2" instead:</p>
<pre>
&lt;html&gt;
&lt;body&gt;
	&lt;form id=&quot;upload&quot; action=&quot;/fileUpload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
		&lt;input type=&quot;file&quot; name=&quot;file2&quot; size=&quot;40&quot;&gt;
		&lt;input type=submit value=&quot;Upload!&quot;&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>REST Assured still makes it simple:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file2&quot;</span>, <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><span style="color: #ff0000;">&quot;/home/johan/some_large_file.bin&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;fileUploadResult&quot;</span>, is<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;OK&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">post</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/fileUpload&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Multiple parts</h2>
<p>You can even send multiple files, streams, byte-arrays and form parameters in the same request:</p>
<pre class="java">&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInputStream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">InputStream</span></a> inputStream = ..
&nbsp;
<span style="color: #006600;">given</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file1&quot;</span>, <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><span style="color: #ff0000;">&quot;/home/johan/some_large_file.bin&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file2&quot;</span>, <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><span style="color: #ff0000;">&quot;/home/johan/some_other_large_file.bin&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file3&quot;</span>, <span style="color: #ff0000;">&quot;file_name.bin&quot;</span>, inputStream<span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">formParam</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;name&quot;</span>, <span style="color: #ff0000;">&quot;value&quot;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;fileUploadResult&quot;</span>, is<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;OK&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">post</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/advancedFileUpload&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Summary</h2>
<p>As you've hopefully seen it's very simple do multi-part form data uploading with REST Assured. Credits should of course also go to <a href="http://hc.apache.org/">Apache HTTP Client</a> for making it possible. To get started with REST Assured today just visit the <a href="http://code.google.com/p/rest-assured/">web-site</a>. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Is your REST assured?</title>
		<link>http://blog.jayway.com/2011/06/04/is-your-rest-assured/</link>
		<comments>http://blog.jayway.com/2011/06/04/is-your-rest-assured/#comments</comments>
		<pubDate>Sat, 04 Jun 2011 08:01:33 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8558</guid>
		<description><![CDATA[A couple of months ago I introduced a new open source Java framework for simple automated testing of REST/HTTP services called REST Assured. A lot of things have happended to the framework since then and it's now better than ever. In this blog I'm going to summarize some of the most important new features that [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of months ago I <a href="http://blog.jayway.com/2010/12/27/rest-assured-or-how-to-easily-test-rest-services-in-java/">introduced</a> a new open source Java framework for simple automated testing of REST/HTTP services called <a href="http://code.google.com/p/rest-assured/">REST Assured</a>. A lot of things have happended to the framework since then and it's now better than ever. In this blog I'm going to summarize some of the most important new features that have been added since the last blog post.</p>
<h3>Easy parsing of the response body</h3>
<h4>JSON</h4>
<p>Let's assume that a REST service at <code>localhost:8080/json</code> returns:</p>
<pre class="javascript">&nbsp;
<span style="color: #66cc66;">&#123;</span>
<span style="color: #3366CC;">&quot;lotto&quot;</span>:<span style="color: #66cc66;">&#123;</span>
 <span style="color: #3366CC;">&quot;lottoId&quot;</span>:<span style="color: #CC0000;">5</span>,
 <span style="color: #3366CC;">&quot;winning-numbers&quot;</span>:<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">2</span>,<span style="color: #CC0000;">45</span>,<span style="color: #CC0000;">34</span>,<span style="color: #CC0000;">23</span>,<span style="color: #CC0000;">7</span>,<span style="color: #CC0000;">5</span>,<span style="color: #CC0000;">3</span><span style="color: #66cc66;">&#93;</span>,
 <span style="color: #3366CC;">&quot;winners&quot;</span>:<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#123;</span>
   <span style="color: #3366CC;">&quot;winnerId&quot;</span>:<span style="color: #CC0000;">23</span>,
   <span style="color: #3366CC;">&quot;numbers&quot;</span>:<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">2</span>,<span style="color: #CC0000;">45</span>,<span style="color: #CC0000;">34</span>,<span style="color: #CC0000;">23</span>,<span style="color: #CC0000;">3</span>,<span style="color: #CC0000;">5</span><span style="color: #66cc66;">&#93;</span>
 <span style="color: #66cc66;">&#125;</span>,<span style="color: #66cc66;">&#123;</span>
   <span style="color: #3366CC;">&quot;winnerId&quot;</span>:<span style="color: #CC0000;">54</span>,
   <span style="color: #3366CC;">&quot;numbers&quot;</span>:<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">52</span>,<span style="color: #CC0000;">3</span>,<span style="color: #CC0000;">12</span>,<span style="color: #CC0000;">11</span>,<span style="color: #CC0000;">18</span>,<span style="color: #CC0000;">22</span><span style="color: #66cc66;">&#93;</span>
 <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>As a recap let's say you want to validate that the lottoId is equal to 5 and winnerIds are 23 and 54 you can do like this:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.lottoId&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.winners.winnderId&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">23</span>, <span style="color: #cc66cc;">54</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>where "equalTo" and "hasItems" are standard <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> matchers. But what if you want to return the lottoId or winnder id's and do something with the values? For this reason <a href="http://rest-assured.googlecode.com/svn/tags/1.2.1/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> has been added to REST Assured. Example:</p>
<pre class="java">&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> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Assuming we've statically imported the &quot;from&quot; method in JsonPath we can do:</span>
<span style="color: #993333;">int</span> lottoId = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.lottoId&quot;</span><span style="color: #66cc66;">&#41;</span>;
List&lt;Integer&gt; winnerIds = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.winners.winnderId&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
..
&nbsp;</pre>
<p>You can also set a so called "root path" so that you don't have to repeat the entire path for every "get":</p>
<pre class="java">&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> responseString = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
JsonPath response = <span style="color: #000000; font-weight: bold;">new</span> JsonPath<span style="color: #66cc66;">&#40;</span>responseString<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">setRoot</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> lottoId = response.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lottoId&quot;</span><span style="color: #66cc66;">&#41;</span>;
List&lt;Integer&gt; winnerIds = response.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;winners.winnderId&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>XML</h3>
<p>The equilvant of JsonPath for XML is called <a href="http://rest-assured.googlecode.com/svn/tags/1.2.1/apidocs/com/jayway/restassured/path/xml/XmlPath.html">XmlPath</a> and it works in very much the same way as JsonPath but arguably a bit more complex because of the nature of XML. Consider the following XML available at <code>localhost:8080/xml</code>:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;records<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;car</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">'HSV Maloo'</span> <span style="color: #000066;">make</span>=<span style="color: #ff0000;">'Holden'</span> <span style="color: #000066;">year</span>=<span style="color: #ff0000;">'2006'</span><span style="font-weight: bold; color: black;">&gt;</span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;country<span style="font-weight: bold; color: black;">&gt;</span></span></span>Australia<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/country<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;record</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">'speed'</span><span style="font-weight: bold; color: black;">&gt;</span></span>Pickup Truck with speed of 271kph<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/record<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/car<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;car</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">'P50'</span> <span style="color: #000066;">make</span>=<span style="color: #ff0000;">'Peel'</span> <span style="color: #000066;">year</span>=<span style="color: #ff0000;">'1962'</span><span style="font-weight: bold; color: black;">&gt;</span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;country<span style="font-weight: bold; color: black;">&gt;</span></span></span>Isle of Man<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/country<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;record</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">'size'</span><span style="font-weight: bold; color: black;">&gt;</span></span>Street-Legal Car at 99cm wide, 59kg<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/record<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/car<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/records<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Now let's make a request and parse the XML:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the XML from localhost:8080/xml</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> xml = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/xml&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Get the country of the first car (“from” is statically imported from from XmlPath)</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> country = from<span style="color: #66cc66;">&#40;</span>xml<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;records.car[0].country”);
&nbsp;
// Get a list of all car names
List&lt;String&gt; carNames = from(xml).get(&quot;</span>records.<span style="color: #006600;">car</span>.@name<span style="color: #ff0000;">&quot;);
</span></pre>
<p>As with JsonPath you can also set a root path to make it a bit more efficient:</p>
<pre class="java">&nbsp;
XmlPath xmlPath = <span style="color: #000000; font-weight: bold;">new</span> XmlPath<span style="color: #66cc66;">&#40;</span>xml<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">setRoot</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;records&quot;</span><span style="color: #66cc66;">&#41;</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> country = xmlPath.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;car[0].country&quot;</span><span style="color: #66cc66;">&#41;</span>;
List&lt;String&gt; carNames = xmlPath.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;car.@name&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Filters</h2>
<p>Another powerful feature is support for filters. A filter allows you to inspect and alter a request before it's actually committed and also inspect and alter the response before it's returned to the expectations. You can regard it as an "around advice" in AOP terms. Filters can be used to implement custom authentication schemes, session management, logging etc. To create a filter you need to implement the com.jayway.restassured.filter.log.Filter interface. Here's an example filter that simply logs the response body to the console:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SystemOutFilter <span style="color: #000000; font-weight: bold;">implements</span> Filter <span style="color: #66cc66;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Response filter<span style="color: #66cc66;">&#40;</span>FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">final</span> Response response = ctx.<span style="color: #006600;">next</span><span style="color: #66cc66;">&#40;</span>requestSpec, responseSpec<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// Invoke the request by delegating to the next filter in the filter chain.</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;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>response.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">return</span> response;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>You can then apply your filter like this:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">filter</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SystemOutFilter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>. ..
&nbsp;</pre>
<p>REST Assured already comes with two pre-defined logging filters called <a href="http://rest-assured.googlecode.com/svn/tags/1.2.1/apidocs/com/jayway/restassured/filter/log/ResponseLoggingFilter.html">ResponseLoggingFilter</a> and <a href="http://rest-assured.googlecode.com/svn/tags/1.2.1/apidocs/com/jayway/restassured/filter/log/ErrorLoggingFilter.html">ErrorLoggingFilter</a> are there's also shortcuts for using these filters (see below).</p>
<h2>Logging</h2>
<p>When writing a test it's often useful to see what the response body actually looks like. To easily accomodate this REST Assured provides a shortcut for adding the two logging filters introduced in the previous section. So to log the response body regardless of the status code you can just do:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.lottoId&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.winners.winnderId&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">23</span>, <span style="color: #cc66cc;">54</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>If you only which to log when an error occurs you can do:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">logOnError</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.lottoId&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.winners.winnderId&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">23</span>, <span style="color: #cc66cc;">54</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Form authentication</h2>
<p>Form authentication is one of the most popular authentication techniques on the net today and using REST Assured it's very simple to test services requiring this scheme. Imagine that the request to <code>localhost:8080/json</code> requires form authentication, we can then do:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">auth</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">form</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;username&quot;</span>, <span style="color: #ff0000;">&quot;password&quot;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.lottoId&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.winners.winnderId&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">23</span>, <span style="color: #cc66cc;">54</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>In many cases it's as simple as that! Basically what happens is that REST Assured parses the login page and logs in for you before making the original request. But if you have many tests or if REST Assured is not able to parse the login page you can supply something called a FormAuthConfig to tell REST Assured how to login. What you provide is the form action and the user name and password input tags. This option will also make your test run faster since there's no need for REST Assured to make an additional requests and parse the login page. For example:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">auth</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">form</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;username&quot;</span>, <span style="color: #ff0000;">&quot;password&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> FilterConfig<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/action&quot;</span>, <span style="color: #ff0000;">&quot;usernameField&quot;</span>, <span style="color: #ff0000;">&quot;passwordField&quot;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">logOnError</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.lottoId&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.winners.winnderId&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">23</span>, <span style="color: #cc66cc;">54</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>If you're using Spring Security there's a pre-defined FilterAuthConfig:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">auth</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">form</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;username&quot;</span>, <span style="color: #ff0000;">&quot;password&quot;</span>, FilterConfig.<span style="color: #006600;">springSecurity</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
&nbsp;</pre>
<h2>Reusable specifications</h2>
<p>Instead of having to duplicate response expectations and/or request parameters for different tests you can re-use an entire specification. To do this you define a specification using either the RequestSpecBuilder or ResponseSpecBuilder.</p>
<p>E.g. let's say you want to make sure that the expected status code is 200 and that JSON the size of the JSON array "x.y" has size 2 in several tests you can define a ResponseSpecBuilder like this:</p>
<pre class="java">&nbsp;
ResponseSpecBuilder builder = <span style="color: #000000; font-weight: bold;">new</span> ResponseSpecBuilder<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
builder.<span style="color: #006600;">expectStatusCode</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">200</span><span style="color: #66cc66;">&#41;</span>;
builder.<span style="color: #006600;">expectBody</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;x.y.size()&quot;</span>, is<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
ResponseSpecification responseSpec = builder.<span style="color: #006600;">build</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Now you can re-use the &quot;responseSpec&quot; in many different tests:</span>
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
       <span style="color: #006600;">spec</span><span style="color: #66cc66;">&#40;</span>responseSpec<span style="color: #66cc66;">&#41;</span>.
       <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;x.y.z&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/something&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>In this example the data defined in "responseSpec" is merged with the additional body expectation and all expectations must be fulfilled in order for the test to pass.</p>
<p>You can do the same thing if you need to re-use request data in different tests. E.g.</p>
<pre class="java">&nbsp;
RequestSpecBuilder builder = <span style="color: #000000; font-weight: bold;">new</span> RequestSpecBuilder<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
builder.<span style="color: #006600;">addParameter</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;parameter1&quot;</span>, <span style="color: #ff0000;">&quot;parameterValue&quot;</span><span style="color: #66cc66;">&#41;</span>;
builder.<span style="color: #006600;">addHeader</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;header1&quot;</span>, <span style="color: #ff0000;">&quot;headerValue&quot;</span><span style="color: #66cc66;">&#41;</span>;
RequestSpecification requestSpec = builder.<span style="color: #006600;">build</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">spec</span><span style="color: #66cc66;">&#40;</span>requestSpec<span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">param</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;parameter2&quot;</span>, <span style="color: #ff0000;">&quot;paramValue&quot;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;x.y.z&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</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: #ff0000;">&quot;/something&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Here the request's data is merged with the data in the "requestSpec" so the request will contain two parameters ("parameter1" and "parameter2") and one header ("header1").</p>
<h2>Summary</h2>
<p>As you've hopefully seen there are many new useful features added to REST Assured. Other new features that have not been mentioned in this post are e.g. improved HTML parsing, very simple XSD/DTD validation, multi-value parameters, setting root path on expectations, improved configuration of default settings etc etc. In the future we'll hope to add support for JSONP, better XML parsing using XmlPath and a more BDD-like (given, when, then) syntax. Please visit our <a href="http://code.google.com/p/rest-assured/">homepage</a> for more information and downloads.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/06/04/is-your-rest-assured/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PowerMock for Integration Testing</title>
		<link>http://blog.jayway.com/2011/05/19/powermock-for-integration-testing/</link>
		<comments>http://blog.jayway.com/2011/05/19/powermock-for-integration-testing/#comments</comments>
		<pubDate>Thu, 19 May 2011 19:34:03 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[testng]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8404</guid>
		<description><![CDATA[A while ago I blogged about how to use the PowerMock Rule to bootstrap PowerMock without using a JUnit runner. A problem that you'll likely run into sooner or later when using this approach in an integration test is the need to ignore certain classes or packages from being loaded by the PowerMock classloader using [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I <a href="http://blog.jayway.com/2010/12/28/using-powermock-with-spring-integration-testing/">blogged</a> about how to use the <a href="http://www.powermock.org">PowerMock</a> <a href="http://code.google.com/p/powermock/wiki/PowerMockRule">Rule</a> to bootstrap PowerMock without using a JUnit runner. A problem that you'll likely run into sooner or later when using this approach in an integration test is the need to ignore certain classes or packages from being loaded by the PowerMock classloader using the <code>@PowerMockIgnore</code> annotation. This is actually not limited to the Rule but happens when using the standard JUnit runner as well but it's much more likely to occur in an integration test. Frequent candidates for this are various XML, log, and persistence frameworks . The reason is that some frameworks tries to instantiate classes using reflection and does this from the thread context classloader (PowerMock's classloader) but then tries to assign the created object to a field not loaded by the same classloader. So by using <code>@PowerMockIgnore</code> you can can instruct PowerMock to defer the loading of a certain package to the parent classloader. What you need to ignore is case specific but usually it's e.g. the XML framework or some packages that interact with it. E.g. <code>@PowerMockIgnore({"org.xml.*", "javax.xml.*"})</code>. </p>
<h2>Example</h2>
<p>Let's say we have a (very stupid) Spring bean like this:</p>
<pre class="java">&nbsp;
@<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AComponent+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Component</span></a>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyBean <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">private</span> CompanyRepository companyRepository;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Message generateMessage<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> SAXException <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><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> allEmployees = companyRepository.<span style="color: #006600;">getAllEmployees</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</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> message = StringUtils.<span style="color: #006600;">join</span><span style="color: #66cc66;">&#40;</span>allEmployees, <span style="color: #ff0000;">&quot;, &quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <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: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Message<span style="color: #66cc66;">&#40;</span>id, message<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and for demonstration we'd like to mock the static method call to <code>IdGenerator.generateNewId()</code>. Let's write a simple test bootstrapped by Spring using the <a href="http://code.google.com/p/powermock/wiki/PowerMockRule">classloader</a> version of PowerMockRule:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;classpath:/example-context.xml&quot;</span><span style="color: #66cc66;">&#41;</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> SpringExampleTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Rule
    <span style="color: #000000; font-weight: bold;">public</span> PowerMockRule rule = <span style="color: #000000; font-weight: bold;">new</span> PowerMockRule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">private</span> MyBean myBean;
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockStaticMethod<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: #808080; font-style: italic;">// Given</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> expectedId = 2L;
        mockStatic<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</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>expectedId<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</span>
        <span style="color: #000000; font-weight: bold;">final</span> Message message = myBean.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span>expectedId, message.<span style="color: #006600;">getId</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><span style="color: #ff0000;">&quot;John Doe, Paul Anderson, Jane Doe&quot;</span>, message.<span style="color: #006600;">getContent</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>
&nbsp;</pre>
<p>If you run this test you'll get the following error:</p>
<pre class="java">&nbsp;
java.<span style="color: #006600;">lang</span>.<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ARuntimeException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">RuntimeException</span></a>: java.<span style="color: #006600;">lang</span>.<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AClassCastException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">ClassCastException</span></a>: com.<span style="color: #006600;">sun</span>.<span style="color: #006600;">org</span>.<span style="color: #006600;">apache</span>.<span style="color: #006600;">xerces</span>.<span style="color: #006600;">internal</span>.<span style="color: #006600;">jaxp</span>.<span style="color: #006600;">DocumentBuilderFactoryImpl</span> cannot be cast to javax.<span style="color: #006600;">xml</span>.<span style="color: #006600;">parsers</span>.<span style="color: #006600;">DocumentBuilderFactory</span>
	at powermock.<span style="color: #006600;">examples</span>.<span style="color: #006600;">spring</span>.<span style="color: #006600;">CompanyRepository</span>.<span style="color: #006600;">getAllEmployees</span><span style="color: #66cc66;">&#40;</span>CompanyRepository.<span style="color: #006600;">java</span>:<span style="color: #cc66cc;">42</span><span style="color: #66cc66;">&#41;</span>
	at powermock.<span style="color: #006600;">examples</span>.<span style="color: #006600;">spring</span>.<span style="color: #006600;">MyBean</span>.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span>MyBean.<span style="color: #006600;">java</span>:<span style="color: #cc66cc;">31</span><span style="color: #66cc66;">&#41;</span>
	at org.<span style="color: #006600;">powermock</span>.<span style="color: #006600;">examples</span>.<span style="color: #006600;">spring</span>.<span style="color: #006600;">mockito</span>.<span style="color: #006600;">SpringExampleTest</span>.<span style="color: #006600;">mockStaticMethod</span><span style="color: #66cc66;">&#40;</span>SpringExampleTest.<span style="color: #006600;">java</span>:<span style="color: #cc66cc;">58</span><span style="color: #66cc66;">&#41;</span>
...
&nbsp;</pre>
<p>The reason is that <code>companyRepository.getAllEmployees()</code> implementation called from <code>MyBean</code> bean above parses the employee list using Java's XML parsing (<code>javax.xml.parsers.DocumentBuilderFactory</code>). Thus we must use the PowerMockIgnore annotation to ignore the framework:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;classpath:/example-context.xml&quot;</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@PowerMockIgnore<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span><span style="color: #ff0000;">&quot;org.w3c.*&quot;</span>, <span style="color: #ff0000;">&quot;javax.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> SpringExampleTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Rule
    <span style="color: #000000; font-weight: bold;">public</span> PowerMockRule rule = <span style="color: #000000; font-weight: bold;">new</span> PowerMockRule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    ....
    <span style="color: #808080; font-style: italic;">// Same code as in the previous example</span>
&nbsp;</pre>
<p>Re-run the test and it'll now pass. </p>
<h2>Introducing PowerMock Java Agent</h2>
<p>To make it easier to use PowerMock for integration testing version 1.4.9 introduces yet another way to bootstrap the framework, this time using a <a href="http://code.google.com/p/powermock/wiki/PowerMockAgent">java agent</a>. Instead of using classloaders to bootstrap and perform byte-code manipulation we now use Java's instrumentation API. This means that you won't run into classloading issues as those presented in the previous example. The test looks exactly the same though:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;classpath:/example-context.xml&quot;</span><span style="color: #66cc66;">&#41;</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> SpringExampleTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Rule
    <span style="color: #000000; font-weight: bold;">public</span> PowerMockRule rule = <span style="color: #000000; font-weight: bold;">new</span> PowerMockRule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">private</span> MyBean myBean;
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockStaticMethod<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: #808080; font-style: italic;">// Given</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> expectedId = 2L;
        mockStatic<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</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>expectedId<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</span>
        <span style="color: #000000; font-weight: bold;">final</span> Message message = myBean.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span>expectedId, message.<span style="color: #006600;">getId</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><span style="color: #ff0000;">&quot;John Doe, Paul Anderson, Jane Doe&quot;</span>, message.<span style="color: #006600;">getContent</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>
&nbsp;</pre>
<p>Even though the test looks exactly the same the internal implementation has a lot of differences. To have a look at the real code behind the to examples have a look in subversion <a href="http://powermock.googlecode.com/svn/tags/powermock-1.4.9/examples/spring-mockito-xml">here</a> for the first example  and <a href="http://powermock.googlecode.com/svn/tags/powermock-1.4.9/examples/spring-mockito-xml-agent">here</a> for the java agent example.</p>
<h2>Round-up</h2>
<p>Using the Java agent can help you out when you run into hard-to-resolve classloading issues with PowerMock. The implementation is still experimental and we are aware of some bugs and limitations. To know more and find help getting started with the agent please have a look at the <a href="http://code.google.com/p/powermock/wiki/PowerMockAgent">documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/19/powermock-for-integration-testing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PowerMock with unsupported frameworks such as JMock</title>
		<link>http://blog.jayway.com/2010/12/28/powermock-with-unsupported-frameworks-such-as-jmock/</link>
		<comments>http://blog.jayway.com/2010/12/28/powermock-with-unsupported-frameworks-such-as-jmock/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 18:47:45 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[jmock]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6844</guid>
		<description><![CDATA[Currently PowerMock builds on top of EasyMock and Mockito to provide mocking of e.g. static methods and final classes using a familiar API. What most people don't know is that it's pretty easy to benefit from PowerMock even for frameworks it doesn't support. JMock is another popular mocking framework that PowerMock currently doesn't support but [...]]]></description>
			<content:encoded><![CDATA[<p>Currently <a href="http://www.powermock.org">PowerMock</a> builds on top of <a href="http://easymock.org/">EasyMock</a> and <a href="http://www.mockito.org/">Mockito</a> to provide mocking of e.g. static methods and final classes using a familiar API. What most people don't know is that it's pretty easy to benefit from PowerMock even for frameworks it doesn't support. <a href="http://www.jmock.org/">JMock</a> is another popular mocking framework that PowerMock currently doesn't support but this article will demonstrate some examples of JMock and PowerMock.</p>
<h2>Mocking final classes</h2>
<p>Unlike EasyMock and Mockito, JMock doesn't support mocking classes out of the box. For this to work you need to have the <code>jmock-legacy</code> jar file in your classpath. But even if you have you cannot mock classes that are final:</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> FinalClass <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> helloWorld<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: #ff0000;">&quot;Hello world&quot;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>But here PowerMock can help. What you need to do is to use the PowerMock JUnit runner and to prepare the <code>FinalClass</code> for 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>FinalClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>But unfortunately this is not enough. For PowerMock to work it needs something called a "ProxyFrameworkImpl" that helps the reflection utilities in PowerMock to find an unproxied class type of a proxied class. It also needs an "AnnotationEnabler" that's used for injecting mocks. This may sound complicated but since JMock is using CGLib to create class proxies you can use PowerMock's EasyMock implementation of the "ProxyFrameworkImpl" and "AnnotationEnabler". This works because EasyMock is also using CGLib. Thus you need to put the <a href="http://repo1.maven.org/maven2/org/powermock/powermock-api-easymock/1.4.7/powermock-api-easymock-1.4.7.jar">powermock-api-easymock.jar</a> in your class-path (note that you don't need the easymock.jar in the classpath).</p>
<p>Once we have the <a href="http://repo1.maven.org/maven2/org/powermock/powermock-api-easymock/1.4.7/powermock-api-easymock-1.4.7.jar">powermock-api-easymock.jar</a> in the classpath and have added the two annotations we're ready to test the FinalClass. Here's a full example:</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>FinalClass.<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> JMockFinalClassTest <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Mockery context = <span style="color: #000000; font-weight: bold;">new</span> JUnit4Mockery<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#123;</span>
        setImposteriser<span style="color: #66cc66;">&#40;</span>ClassImposteriser.<span style="color: #006600;">INSTANCE</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;">private</span> FinalClass tested;
&nbsp;
    @Before
    <span style="color: #000000; font-weight: bold;">public</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>
        tested = context.<span style="color: #006600;">mock</span><span style="color: #66cc66;">&#40;</span>FinalClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockFinalClassWithPowerMockAndJMock<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: #808080; font-style: italic;">// Given</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;something&quot;</span>;
        context.<span style="color: #006600;">checking</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Expectations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#123;</span>
            one<span style="color: #66cc66;">&#40;</span>tested<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">helloWorld</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            will<span style="color: #66cc66;">&#40;</span>returnValue<span style="color: #66cc66;">&#40;</span>expected<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;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</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> actual = tested.<span style="color: #006600;">helloWorld</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span>expected, actual<span style="color: #66cc66;">&#41;</span>;
        context.<span style="color: #006600;">assertIsSatisfied</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>
<h2><del>Mocking</del> Stubbing static methods</h2>
<p>Now that we know how to mock final classes, how about static methods? The bad news is that you can't mock them. But the good news on the other hand is that PowerMock provides a <a href="http://powermock.googlecode.com/svn/docs/powermock-1.4.7/apidocs/org/powermock/api/support/membermodification/MemberModifier.html">MemberModification</a> API that allows you to stub, suppress and replace methods. So to stub a static method regardless of the underlying mock framework you can do:</p>
<pre class="java">&nbsp;
stub<span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>ClassWithStaticMethod.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;staticMethodName&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">toReturn</span><span style="color: #66cc66;">&#40;</span>someObject<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>To demonstrate how this can be used with JMock imagine that we want to test the <code>generateMessage</code> method in this example:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JMockExample <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> FinalClass finalClass;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> JMockExample<span style="color: #66cc66;">&#40;</span>FinalClass finalClass<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;">finalClass</span> = finalClass;
    <span style="color: #66cc66;">&#125;</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> generateMessage<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: #ff0000;">&quot;Message is: &quot;</span>+ finalClass.<span style="color: #006600;">helloWorld</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + ClassWithStaticMethod.<span style="color: #006600;">returnString</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>where <code>FinalClass</code> is the same as in the previous example and <code>ClassWithStaticMethod</code> looks like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ClassWithStaticMethod <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> returnString<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: #ff0000;">&quot;a string&quot;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>A full JMock test with PowerMock can look like this:</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>FinalClass.<span style="color: #000000; font-weight: bold;">class</span>, ClassWithStaticMethod.<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> JMockStaticMethodTest <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Mockery context = <span style="color: #000000; font-weight: bold;">new</span> JUnit4Mockery<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#123;</span>
        setImposteriser<span style="color: #66cc66;">&#40;</span>ClassImposteriser.<span style="color: #006600;">INSTANCE</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;">private</span> FinalClass finalClassMock;
    <span style="color: #000000; font-weight: bold;">private</span> JMockExample tested;
&nbsp;
    @Before
    <span style="color: #000000; font-weight: bold;">public</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>
        finalClassMock = context.<span style="color: #006600;">mock</span><span style="color: #66cc66;">&#40;</span>FinalClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
        tested = <span style="color: #000000; font-weight: bold;">new</span> JMockExample<span style="color: #66cc66;">&#40;</span>finalClassMock<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> stubbingAndMockingWithPowerMockAndJMock<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: #808080; font-style: italic;">// Given</span>
        context.<span style="color: #006600;">checking</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Expectations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#123;</span>
            one<span style="color: #66cc66;">&#40;</span>finalClassMock<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">helloWorld</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            will<span style="color: #66cc66;">&#40;</span>returnValue<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Hello &quot;</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;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Stub the static method</span>
        stub<span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>ClassWithStaticMethod.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;returnString&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">toReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;JMock&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</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> message = tested.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Message is: Hello JMock&quot;</span>, message<span style="color: #66cc66;">&#41;</span>;
        context.<span style="color: #006600;">assertIsSatisfied</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>You can check out the examples from our <a href="http://powermock.googlecode.com/svn/trunk/examples/jmock/">SVN repo</a>.</p>
<h2>Notes</h2>
<p>JMock also provides its own JUnit runner called "JMock" that automatically calls <code>context.assertIsSatisfied()</code> after each test. Normally you can use PowerMock with other JUnit runners using the <a href="http://code.google.com/p/powermock/wiki/PowerMockRule">PowerMockRule</a> but unfortunatley the JMock runner extends from a deprecated runner which doesn't support rules.</p>
<h2>Conclusion</h2>
<p>As you can see it's pretty simple to use some PowerMock basics even for unsupported frameworks as JMock. Of course it's possible to create full-blown support for JMock using PowerMock to enable e.g. new instance and static method mocking but until that day it's good to know that alternatives exist. If you're interested to know more about PowerMock please visit our <a href="http://www.powermock.org">webpage</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/12/28/powermock-with-unsupported-frameworks-such-as-jmock/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using PowerMock with Spring integration testing</title>
		<link>http://blog.jayway.com/2010/12/28/using-powermock-with-spring-integration-testing/</link>
		<comments>http://blog.jayway.com/2010/12/28/using-powermock-with-spring-integration-testing/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 16:13:51 +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[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6827</guid>
		<description><![CDATA[I quite often get the question if PowerMock can be used together with Spring integration testing or other frameworks that require a JUnit runner to bootstrap. The answer up until now has been somewhat ambiguous. The reason is that for the last year or so we've been working with a new way of bootstrapping PowerMock [...]]]></description>
			<content:encoded><![CDATA[<p>I quite often get the question if <a href="http://www.powermock.org">PowerMock</a> can be used together with Spring integration testing or other frameworks that require a JUnit runner to bootstrap. The answer up until now has been somewhat ambiguous. The reason is that for the last year or so we've been working with a new way of bootstrapping PowerMock that uses a <a href="http://www.infoq.com/news/2009/07/junit-4.7-rules">JUnit Rule</a> instead of a JUnit runner. Implementing this rule proved to be quite hard since it required deep-cloning of an entire object graph into another classloader (more info about this <a href="http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/">here</a>). For example we ran into very strange problems that caused the JVM to crash on some environments while it worked in others. In the new release of PowerMock 1.4.7 we refactored the classloader execution from the deep-cloning and made the deep-cloning implementations pluggable. This means that we now have an option to use <a href="http://xstream.codehaus.org/">X-Stream</a> as deepcloner which proves to be more robust than our <a href="http://code.google.com/p/objenesis/">Objenesis</a> implementation (albeit not as fast, not as precise and not as cool <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).</p>
<h2>Naive example</h2>
<p>Let's say we have a very simple Spring bean like this:</p>
<pre class="java">&nbsp;
@<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AComponent+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Component</span></a>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyBean <span style="color: #66cc66;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Message generateMessage<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: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Message<span style="color: #66cc66;">&#40;</span>id, <span style="color: #ff0000;">&quot;My bean message&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and we want to test the <code>generateMessage</code> method in an integration test. In this test we assume that it's really important for us to mock the static call to <code>IdGenerator.generateNewId()</code>. But in order to run the test as a Spring integration test we need to use the <code>SpringJUnit4ClassRunner</code> which prevents us from using the <code>PowerMockRunner</code>. So by taking advantage of the <code>PowerMockRule</code> we can still benefit from PowerMock's functionality:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;classpath:/example-context.xml&quot;</span><span style="color: #66cc66;">&#41;</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> SpringExampleTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Rule
    <span style="color: #000000; font-weight: bold;">public</span> PowerMockRule rule = <span style="color: #000000; font-weight: bold;">new</span> PowerMockRule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">private</span> MyBean myBean;
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockStaticMethod<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: #808080; font-style: italic;">// Given</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> expectedId = 2L;
        mockStatic<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</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>expectedId<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</span>
        <span style="color: #000000; font-weight: bold;">final</span> Message message = myBean.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span>expectedId, message.<span style="color: #006600;">getId</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><span style="color: #ff0000;">&quot;My bean message&quot;</span>, message.<span style="color: #006600;">getContent</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>
&nbsp;</pre>
<p>If you're used to PowerMock you can see that the only difference between this test and a standard PowerMock test is that we use the <code>PowerMockRule</code> instead of the </code>PowerMockRunner</code>. You can find the complete example in our SVN <a href="http://powermock.googlecode.com/svn/tags/powermock-1.4.7/examples/spring-mockito">repo</a>.</p>
<h2>Limitations</h2>
<p>For trivial tests like this the Objenesis deep-cloner works just as well as the X-Stream version but in more complex situations X-Stream is more robust. There may still be bugs lurking around and we're thankful for contributions. For example it's not possible to mock <a href="http://code.google.com/p/powermock/wiki/MockSystem">system classes</a> using any of the implementations yet.</p>
<h2>Conclusion</h2>
<p>We'll continue to work on the Objenesis deep-cloner but until it's working better you can use the X-Stream version to combine PowerMock with frameworks that require a JUnit runner. Please refer to <a href="http://code.google.com/p/powermock/wiki/PowerMockRule">this page</a> to get started with the rule.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/12/28/using-powermock-with-spring-integration-testing/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>REST Assured &#8211; Or how to easily test REST services in Java</title>
		<link>http://blog.jayway.com/2010/12/27/rest-assured-or-how-to-easily-test-rest-services-in-java/</link>
		<comments>http://blog.jayway.com/2010/12/27/rest-assured-or-how-to-easily-test-rest-services-in-java/#comments</comments>
		<pubDate>Mon, 27 Dec 2010 08:42:01 +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[rest]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6816</guid>
		<description><![CDATA[Testing and validating REST services in Java is harder than in dynamic languages such as Ruby and Groovy. REST Assured is a Java DSL (built on top of HTTP Builder) that brings the simplicity of these languages into the Java domain. Example 1 - JSON Assume that a GET request to http://localhost:8080/lotto returns JSON as: [...]]]></description>
			<content:encoded><![CDATA[<p>Testing and validating REST services in Java is harder than in dynamic languages such as Ruby and Groovy. <a href="http://code.google.com/p/rest-assured/">REST Assured</a> is a Java DSL (built on top of <a href="http://groovy.codehaus.org/HTTP+Builder">HTTP Builder</a>) that brings the simplicity of these languages into the Java domain.</p>
<h2>Example 1 - JSON</h2>
<p>Assume that a GET request to http://localhost:8080/lotto returns JSON as:</p>
<pre class="javascript">&nbsp;
<span style="color: #66cc66;">&#123;</span>
 <span style="color: #3366CC;">&quot;lotto&quot;</span>:<span style="color: #66cc66;">&#123;</span>
 <span style="color: #3366CC;">&quot;lottoId&quot;</span>:<span style="color: #CC0000;">5</span>,
 <span style="color: #3366CC;">&quot;winning-numbers&quot;</span>:<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">2</span>,<span style="color: #CC0000;">45</span>,<span style="color: #CC0000;">34</span>,<span style="color: #CC0000;">23</span>,<span style="color: #CC0000;">7</span>,<span style="color: #CC0000;">5</span>,<span style="color: #CC0000;">3</span><span style="color: #66cc66;">&#93;</span>,
 <span style="color: #3366CC;">&quot;winners&quot;</span>:<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#123;</span>
   <span style="color: #3366CC;">&quot;winnerId&quot;</span>:<span style="color: #CC0000;">23</span>,
   <span style="color: #3366CC;">&quot;numbers&quot;</span>:<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">2</span>,<span style="color: #CC0000;">45</span>,<span style="color: #CC0000;">34</span>,<span style="color: #CC0000;">23</span>,<span style="color: #CC0000;">3</span>,<span style="color: #CC0000;">5</span><span style="color: #66cc66;">&#93;</span>
 <span style="color: #66cc66;">&#125;</span>,<span style="color: #66cc66;">&#123;</span>
   <span style="color: #3366CC;">&quot;winnerId&quot;</span>:<span style="color: #CC0000;">54</span>,
   <span style="color: #3366CC;">&quot;numbers&quot;</span>:<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">52</span>,<span style="color: #CC0000;">3</span>,<span style="color: #CC0000;">12</span>,<span style="color: #CC0000;">11</span>,<span style="color: #CC0000;">18</span>,<span style="color: #CC0000;">22</span><span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">&#125;</span>
 <span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>REST assured can then help you to easily make the GET request and verify the response. E.g. if you want to verify that lottoId is equal to 5 you can do like this:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.lottoId&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">when</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: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>or perhaps you want to check that the winnerId's are 23 and 54:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;lotto.winners.winnerId&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">23</span>, <span style="color: #cc66cc;">54</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">when</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: #ff0000;">&quot;/lotto&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Note that <code>equalTo</code> and <code>hasItems</code> are standard <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> matchers.</p>
<h2>Example 2 - XML</h2>
<p>XML can be verified in a similar way. Image that a POST request to http://localhost:8080/greetXML returns:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;greeting<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;firstName<span style="font-weight: bold; color: black;">&gt;</span></span></span>{params(&quot;firstName&quot;)}<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/firstName<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;lastName<span style="font-weight: bold; color: black;">&gt;</span></span></span>{params(&quot;lastName&quot;)}<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/lastName<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/greeting<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>i.e. it sends back a greeting based on the firstName and lastName parameter sent in the request. You can easily perform and verify e.g. the firstName with REST assured:</p>
<pre class="java">&nbsp;
with<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">parameters</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;firstName&quot;</span>, <span style="color: #ff0000;">&quot;John&quot;</span>, <span style="color: #ff0000;">&quot;lastName&quot;</span>, <span style="color: #ff0000;">&quot;Doe&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;greeting.firstName&quot;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;John&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">post</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/greetXML&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>You can also verify XML responses using X-Path. For example:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span>hasXPath<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/greeting/firstName[text()='John']&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: #66cc66;">&#41;</span>.<span style="color: #006600;">parameters</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;firstName&quot;</span>, <span style="color: #ff0000;">&quot;John&quot;</span>, <span style="color: #ff0000;">&quot;lastName&quot;</span>, <span style="color: #ff0000;">&quot;Doe&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">post</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/greetXML&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Authentication</h2>
<p>REST assured also supports some authentication schemes, for example basic authentication:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">auth</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">basic</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;username&quot;</span>, <span style="color: #ff0000;">&quot;password&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">statusCode</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">200</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">when</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: #ff0000;">&quot;/secured/hello&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Other supported schemes are OAuth, Digest and certificate authentication.</p>
<h2>Conclusion</h2>
<p>As you can see it can be really simple to test REST services in Java. REST Assured supports the POST, GET, PUT, DELETE and HEAD http methods and includes specifying and validating e.g. parameters, headers, cookies and body easily. Visit our <a href="http://code.google.com/p/rest-assured/">homepage</a> for more info and downloads.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/12/27/rest-assured-or-how-to-easily-test-rest-services-in-java/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Awaitility 1.3 &#8211; Scala and field support</title>
		<link>http://blog.jayway.com/2010/10/20/awaitility-1-3-scala-and-field-support/</link>
		<comments>http://blog.jayway.com/2010/10/20/awaitility-1-3-scala-and-field-support/#comments</comments>
		<pubDate>Wed, 20 Oct 2010 06:42:31 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6451</guid>
		<description><![CDATA[Awaitility is a Java based DSL that allows you to easily setup expectations for asynchronous code (if you're new to Awaitility you can read an introduction here). Version 1.3 has just been released with a couple of new interesting features. Scala support First of all we now have support for Scala! This means that you [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/awaitility/">Awaitility</a> is a Java based DSL that allows you to easily setup expectations for asynchronous code (if you're new to Awaitility you can read an introduction <a href="http://blog.jayway.com/2010/07/20/awaitility-java-dsl-for-easy-testing-of-asynchronous-systems/">here</a>). Version 1.3 has just been released with a couple of new interesting features. </p>
<h2>Scala support</h2>
<p>First of all we now have support for Scala! This means that you can write your Awaitility code like this:</p>
<pre class="java">&nbsp;
await until <span style="color: #66cc66;">&#123;</span> someMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &gt; <span style="color: #cc66cc;">3</span> <span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>What you actually provide is a no argument function that returns a <code>scala.Boolean</code>. To make this work you simply mixin the <code>AwaitilitySupport</code> trait that is provided in the awaitility-scala module. For more information please refer to the <a href="http://code.google.com/p/awaitility/wiki/Scala">documentation</a>.</p>
<h2>Field suppliers</h2>
<p>Another useful feature is the ability to wait until a field in a class or object has a specific value. In its simplest form you just need to specify the field type. Let's say we have a class with a private field like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Demo <span style="color: #66cc66;">&#123;</span>
    @MyAnnotation
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">volatile</span> <span style="color: #993333;">int</span> myField = <span style="color: #cc66cc;">0</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// Other code goes here</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Using Awaitility field suppliers you can then wait until <code>myField</code> matches something without having to add a getter for the field. For example:</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> fieldIn<span style="color: #66cc66;">&#40;</span>demo<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">ofType</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</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>;
&nbsp;</pre>
<p>Here Awaitility waits until the field of type <code>int</code> in <code>demo</code> equals to 2 or a timeout occurs (default 10 seconds). If you have more than one field of type <code>int</code> in <code>demo</code> you can also specify the field name to uniquely identify the field:</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> fieldIn<span style="color: #66cc66;">&#40;</span>demo<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">ofType</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andWithName</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;myField&quot;</span><span style="color: #66cc66;">&#41;</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>;
&nbsp;</pre>
<p>You can also get the field based on an annotation to avoid specifying a field name:</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> fieldIn<span style="color: #66cc66;">&#40;</span>demo<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">ofType</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andAnnotatedWith</span><span style="color: #66cc66;">&#40;</span>MyAnnotation.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</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>;
&nbsp;</pre>
<p>Important: Awaitility does nothing to ensure thread safety or thread synchronization! This is your responsibility! Make sure your code is correctly synchronized or that you are using thread safe data structures such as volatile fields or classes such as <code>AtomicInteger</code> and <code>ConcurrentHashMap</code>.</p>
<h2>Round off</h2>
<p>We hope you'll find the new release of Awaitility useful. Please refer to the <a href="http://code.google.com/p/awaitility/wiki/ReleaseNotes13">release notes</a> for upgrade information and don't forget to visit our <a href="http://code.google.com/p/awaitility/">home page</a> for downloads.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/10/20/awaitility-1-3-scala-and-field-support/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Awaitility &#8211; Java DSL for easy testing of asynchronous systems</title>
		<link>http://blog.jayway.com/2010/07/20/awaitility-java-dsl-for-easy-testing-of-asynchronous-systems/</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;">untilCall</span><span style="color: #66cc66;">&#40;</span> to<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>to</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>
]]></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>11</slash:comments>
		</item>
		<item>
		<title>Classloader Deep-Cloning without Serialization</title>
		<link>http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/</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>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PowerMock + TestNG = True</title>
		<link>http://blog.jayway.com/2009/12/14/powermock-testng-true/</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>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/14/powermock-testng-true/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Untestable code with Mockito and PowerMock</title>
		<link>http://blog.jayway.com/2009/10/28/untestable-code-with-mockito-and-powermock/</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/mockito/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>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/10/28/untestable-code-with-mockito-and-powermock/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Getting Android SDK working on Ubuntu 64</title>
		<link>http://blog.jayway.com/2009/10/21/getting-android-sdk-working-on-ubuntu-64/</link>
		<comments>http://blog.jayway.com/2009/10/21/getting-android-sdk-working-on-ubuntu-64/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 20:22:34 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2110</guid>
		<description><![CDATA[Today I was trying to setup the Android SDK (version 1.6_r1) on the 64 bit version of Ubuntu 9.04 (Jaunty Jackalope). After having installed the ADT Eclipse plugin and pointed out the Android SDK directory in the settings I immediately ran into the following error: Failed to get the adb version: Cannot run program "/home/johan/devtools/android/android-sdk-linux_x86-1.6_r1/tools/adb": [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was trying to setup the Android SDK (version <a href="http://developer.android.com/sdk/download.html?v=android-sdk-linux_x86-1.6_r1.tgz">1.6_r1</a>)  on the 64 bit version of Ubuntu 9.04 (Jaunty Jackalope). After having installed the <a href="http://dl.google.com/android/ADT-0.9.3.zip">ADT</a> Eclipse plugin and pointed out the Android SDK directory in the settings I immediately ran into the following error: </p>
<pre>
Failed to get the adb version: Cannot run program "/home/johan/devtools/android/android-sdk-linux_x86-1.6_r1/tools/adb": java.io.IOException: error=2, No such file or directory
</pre>
<p>I opened the terminal and tried to manually run an Android executable but even here it said that the file couldn't be found! The problem seemed to be that the Android executables requires 32 bit libraries that are not available in Ubuntu 64 by default. To solve this I downloaded the execellent <a href="http://frozenfox.freehostia.com/cappy/getlibs-all.deb">getlibs</a> application which is a utility for automatically resolving dependencies for 32-bit programs on a 64 bit system. So I went into <code>platforms/android-1.6/tools</code> in the Android SDK installation folder and executed:</p>
<pre class="bash">&nbsp;
getlibs aapt
&nbsp;</pre>
<p>which installed and upgraded the following libraries:</p>
<pre class="bash">&nbsp;
The following NEW packages will be installed:
  ia32-libs lib32asound2 lib32gcc1 lib32ncurses5 lib32stdc+<span style="color: #000000;">+6</span> lib32z1
  libc6-i386
The following packages will be upgraded:
  libc6 libc6-dev
&nbsp;</pre>
<p>After this was done I went back into Eclipse, did a project clean and refresh and after that I was able to start the Android emulator successfully. Hopefully this may help someone who's in the same situation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/10/21/getting-android-sdk-working-on-ubuntu-64/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>Mocking static methods in Java system classes</title>
		<link>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/</link>
		<comments>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/#comments</comments>
		<pubDate>Sun, 17 May 2009 10:34:11 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[tools]]></category>

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

