<?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; automated testing</title>
	<atom:link href="http://blog.jayway.com/tag/automated-testing/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>Testing Web.config Transformations, Part 1</title>
		<link>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/</link>
		<comments>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 20:44:45 +0000</pubDate>
		<dc:creator>Mads Troest</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[transformation]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[Web.config]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11089</guid>
		<description><![CDATA[Web.config transformations is a Microsoft-supported technology for adapting a base configuration to a particular deployment environment. In my previous post, I mentioned how AppHarbor provides an online tool for manually testing transformations. Also, the Visual Studio extension SlowCheetah provides support for manually testing and transformation and diffing them against the base configuration from inside Visual Studio. These [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx" target="_blank">Web.config transformations</a> is a Microsoft-supported technology for adapting a base configuration to a particular deployment environment.</p>
<p>In my <a href="http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/" target="_blank">previous post</a>, I mentioned how <a href="http://appharbor.com" target="_blank">AppHarbor</a> provides an <a href="http://webconfigtransformationtester.apphb.com/" target="_blank">online tool</a> for manually testing transformations. Also, the Visual Studio extension <a href="http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5" target="_blank">SlowCheetah</a> provides support for manually testing and transformation and <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/SlowCheetahPreviewTransform.png" target="_blank">diffing</a> them against the base configuration from inside Visual Studio. These tools are useful and may be fine for tinkering with getting a transform just right, but being software professionals, we find it highly desirable to reliably automate our transformation testing.</p>
<p>In this article we shall look at one way to exercise our Web.config transformations from our own code, so that we can TDD our transformations and regression test them as part of our continuous integration cycle, like everything else.</p>
<h2>Starting Point</h2>
<p>The actual Web.config transformation process is normally invoked by MSBuild, as described in detail by Elton Stoneman in <a href="http://geekswithblogs.net/EltonStoneman/archive/2010/08/20/using-msbuild-4.0-web.config-transformation-to-generate-any-config-file.aspx" target="_blank">this post</a>. (One approach to testing the transformations could, thus, be to fork off MSBuild processes on custom build targets, but we'd like to take a less cumbersome route.)</p>
<p>Being an MSBuild task means that the transformation is implemented as an <strong>ITask</strong> realization. The concrete implementation is called <strong>TransformXml</strong> and resides in the <strong>Microsoft.Web.Publishing.Tasks.dll</strong> assembly. Note that this assembly is not pre-installed with Windows/.NET but rather installed along with Visual Studio 2010, typically to <em>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web</em>). Given that its location is not fixed, you'd probably want to add it to your dependencies folder (caveat emptor: check license terms before passing it around).</p>
<p>From Elton's post, we can also see 3 arguments being passed to the TransformXml task:</p>
<ul>
<li>Source (the XML file to transform)</li>
<li>Transform (the transformation XML file itself)</li>
<li>Destination (the target of the transformed XML file)</li>
</ul>
<p>Armed with that background knowledge, let's move on and try to get the transformation to run outside of the MSBuild environment in which it normally executes. For our experiment, we'll be transforming the following source (<em>app.config</em>):</p>
<pre class="brush: xml;">   &lt;configuration&gt;
     &lt;appSettings&gt;
	   &lt;add key="testKey" value="testValue"/&gt;
     &lt;/appSettings&gt;
   &lt;/configuration&gt;</pre>
<p>The transformation we'll be testing (<em>app.Debug.config</em>) should change the "testValue" of the "testKey" to something transformation specific ("debugValue" in this case):</p>
<pre class="brush: xml;">   &lt;configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"&gt;
     &lt;appSettings&gt;
       &lt;add key="testKey"
            value="debugValue"
            xdt:Locator="Match(key)" xdt:Transform="SetAttributes" /&gt;
     &lt;/appSettings&gt;
   &lt;/configuration&gt;</pre>
<h2>Test Approach</h2>
<p>Our initial stab at automatically testing the transformation will be to invoke the XmlTransform through its outermost interface; i.e. the ITask interface. First, we need to add a reference to <strong>Microsoft.Web.Publishing.Tasks.dll</strong> as mentioned above. Additionally, we need to reference <strong>Microsoft.Build.Framework</strong> and <strong>Microsoft.Build.Utilities.v4.0</strong> (these should be available from your usual <em>Project, Add Reference, .NET </em>tab).</p>
<p>Opening up the XmlTransform class in Visual Studio's Object Browser shows us a single method, <strong>Execute()</strong>, plus a handful of properties, most of which we recognize from Stoneman's previously mentioned post. A little experimentation reveals the following details:</p>
<ul>
<li><strong>SourceRootPath</strong></li>
<ul>
<li>The base path to which the XML file specified in <strong>Source</strong> is relative. If not specified, this will  be the current directory (which, when running from a test runner, would typically be your build target directory).</li>
</ul>
<li><strong>Source</strong></li>
<ul>
<li>The name of the XML source file to be transformed. If this is not an absolute path, it will be relative to the <strong>SourceRootPath</strong>.</li>
</ul>
<li><strong>TransformRootPath</strong></li>
<ul>
<li>The base path to which the XML file specified in <strong>Transform</strong> is relative. If not specified, this will be the same as <strong>SourceRootPath</strong>.</li>
</ul>
<li><strong>Transform</strong></li>
<ul>
<li>The name of the XML transformation to be applied to the source. If this is not an absolute path, it will be relative to the <strong>TransformRootPath</strong>.</li>
</ul>
<li><strong>Destination</strong></li>
<ul>
<li>The name of the resulting transformed XML file. If this is not an absolute path, it will be relative to the current directory (typically your build target directory, in a test context).</li>
</ul>
</ul>
<p>So all we need to do is something like the following, right?</p>
<pre class="brush: csharp;">   var transformer = new TransformXml
   {
      SourceRootPath = @"..\..\..\Jayway.WebTransformTesting\",
      Source = @"app.config",
      Transform = @"app.Debug.config",
      Destination = @"app.transformed.config"
   };
   var transformationSucceeded = transformer.Execute();</pre>
<p>Well, as the <strong>System.InvalidOperationException</strong> with the message <em>"Task attempted to log before it was initialized" </em>thrown in our face subtly tells us, this is not quite the case...</p>
<p>Investigating the task implementation with Reflector shows the problem to be due to the fact that a property, <strong>BuildEngine</strong>, of the Task base class has not been set. It is used as a dependency injection mechanism, giving the task access to some environment services (see <a href="http://msdn.microsoft.com/en-us/library/microsoft.build.framework.ibuildengine.aspx" target="_blank">IBuildEngine</a> on MSDN) normally provided by MSBuild.</p>
<p>Well, the whole purpose of this experiment was to run outside of MSBuild, so we'll roll our own "build engine" instead:</p>
<pre class="brush: csharp;">   public class BuildEngineForTest : IBuildEngine
   {
      public void LogErrorEvent(BuildErrorEventArgs e)
      {
         Console.WriteLine(LogFormat, "ERROR", e.Message);
      }

      public void LogWarningEvent(BuildWarningEventArgs e)
      {
         Console.WriteLine(LogFormat, "WARNING", e.Message);
      }

      public void LogMessageEvent(BuildMessageEventArgs e)
      {
         Console.WriteLine(LogFormat, e.Importance, e.Message);
      }

      public void LogCustomEvent(CustomBuildEventArgs e)
      {
         Console.WriteLine(LogFormat, "CUSTOM", e.Message);
      }

      public bool BuildProjectFile(
         string projectFileName, string[] targetNames,
         IDictionary globalProperties, IDictionary targetOutputs)
      {
         return true;
      }

      public bool ContinueOnError
      {
         get { return true; }
      }

      public int LineNumberOfTaskNode
      {
         get { return 0; }
      }

      public int ColumnNumberOfTaskNode
      {
         get { return 0; }
      }

      public string ProjectFileOfTaskNode
      {
         get { return string.Empty; }
      }

      private const string LogFormat = "{0} : {1}";
   }</pre>
<p>This was the piece we were missing to be able to run the transformation outside MSBuild. We are, thus, able to write our coveted test:</p>
<pre class="brush: csharp;">...
   [Test]
   public void ApplyingDebugTransformationToConfigurationSetsExpectedKey()
   {
      const string targetFile = @"app.transformed.config";

      var transformer = new TransformXml
      {
         BuildEngine = new BuildEngineForTest(),
         SourceRootPath = @"..\..\..\Jayway.WebTransformTesting\",
         Source = @"app.config",
         Transform = @"app.Debug.config",
         Destination = targetFile
      };

      // Left as exercise for the reader... ;]
      AssertKeyInTransformedFile(targetFile);
   }
...</pre>
<p>Our transformation runs successfully, yielding the following console output from our "build engine":</p>
<pre>Normal : Transforming Source File: ..\..\..\Jayway.WebTransformTesting\app.config
Normal : Applying Transform File: ..\..\..\Jayway.WebTransformTesting\app.Debug.config
Low : Executing SetAttributes (transform line 6, 35)
Low : on /configuration/appSettings/add[@key='testKey']
Low : Applying to 'add' element (source line 4, 6)
Low : Set 'key' attribute
Low : Set 'value' attribute
Low : Set 2 attributes
Low : Done executing SetAttributes
Normal : Output File: app.transformed.config
Normal : Transformation succeeded</pre>
<p>Yay? Yay.</p>
<h2>Conclusion</h2>
<p>We have shown how Web.config Transformations can be invoked programmatically, outside the MSBuild process by providing a simple custom IBuildEngine realization; a technique that might prove useful for other scenarios as well.</p>
<p>We have applied that knowledge to enable automated testing of our transformations.</p>
<p>In my next post in this series, we'll continue our investigation, aiming to get rid of the whole, nasty detour around the file system.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Robotium 3.0 &#8211; Stepping It Up!</title>
		<link>http://blog.jayway.com/2011/11/16/robotium-3-0-stepping-it-up-2/</link>
		<comments>http://blog.jayway.com/2011/11/16/robotium-3-0-stepping-it-up-2/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 08:15:56 +0000</pubDate>
		<dc:creator>Renas Reda</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10966</guid>
		<description><![CDATA[For those of you that do not know, Robotium is a test framework used for function and system tests of Android applications. With the release of Robotium 3.0, Robotium is now faster, lighter and more stable then ever! A tremendous amount of work has gone into modifying and improving more or less all the different [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you that do not know, Robotium is a test framework used for function and system tests of Android applications. With the release of Robotium 3.0, Robotium is now faster, lighter and more stable then ever! A tremendous amount of work has gone into modifying and improving more or less all the different portions of the code, making it the most stable version yet. </p>
<p>For me, the most important aspects of Robotium is first most that it is stable and that one can trust the results. Secondly, that it is easy enough to use for non-technical users. A user should not need to be technically inclined to use Robotium or it would have lost its purpose in helping a large user group who know how to write good test cases but lack a bit in the technical area.</p>
<p>Robotium uses a system of waiting for a component before trying to interact with it. The problem with UI testing compared to normal unit tests is that the UI is slow. When writing normal unit tests, the code gets executed in a fast pace by the CPU. That is not the case with the UI. Therefore, UI test cases that are developed without any kind of wait mechanism will sooner or later run into issues. With Robotium 3.0, two completely new waitFor methods have been implemented:</p>
<p><code></p>
<p>waitForView(View view)</p>
<p>waitForView(View view, int timeout, boolean scroll) </code></p>
<p>The various <code>waitFor()</code> methods available in Robotium are used automatically by the, is, get, click, search, scroll and assert methods. However it is always recommended to add additional waitFor calls in your test cases if they will be running on a slow computer or a slow hudson slave. An example of a waitFor method in Robotium that can be beneficial to use is <code>waitForActivity(String name)</code>. The purpose of it is to wait for a certain activity before continuing with the execution. To find out which activity that is active at the moment, you can always look at the log by using <code>adb logcat</code>.</p>
<p>One major change in Robotium 3.0 is that <code>finalize()</code> is now replaced with <code>finishOpenedActivities()</code>. Anyone that has used <code>finalize()</code> before in their <code>tearDown()</code> to close the activities that have been started will need to update their test cases.</p>
<p>If you have not tried Robotium before, I recommend you to first read the <a href="http://code.google.com/p/robotium/wiki/QuestionsAndAnswers">Question and Answers</a> wiki page.</p>
<p>For tutorials please go to the <a href="http://code.google.com/p/robotium/wiki/RobotiumTutorials">Robotium Tutorials</a> wiki page.</p>
<p>To download the javadoc and the latest release of Robotium please go to the <a href="http://code.google.com/p/robotium/downloads/list">Downloads</a> page.</p>
<p>I hope you will enjoy the new and improved Robotium!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/16/robotium-3-0-stepping-it-up-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Infinitest</title>
		<link>http://blog.jayway.com/2011/09/21/infinitest/</link>
		<comments>http://blog.jayway.com/2011/09/21/infinitest/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 20:20:06 +0000</pubDate>
		<dc:creator>Anders Eriksson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[junit]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9572</guid>
		<description><![CDATA[The Infinitest Eclipse plug-in looks for unit tests and have them run as soon as changes are detected. Just as modern IDEs have provided automatic compilation for ages this can now also be provided for unit testing. The test outcome shows up as a green or red bar in the bottom of the Eclipse application [...]]]></description>
			<content:encoded><![CDATA[<p>The <a title="Infinitest" href="http://infinitest.github.com/">Infinitest</a> Eclipse plug-in looks for unit tests and have them run as soon as changes are detected. Just as modern IDEs have provided automatic compilation for ages this can now also be provided for unit testing.</p>
<p>The test outcome shows up as a green or red bar in the bottom of the Eclipse application window. The plugin also gives more feedback. In case of failing test the failing line of code in the unit test shows up with a "problem" icon just as a compilation error would look like. Doing mouse-over on the problem icon you will get the failing assert message. This feature I have noticed in recent versions of Eclipse so try to update to the latest Eclipse if you don't see this happen.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/infinitest12.png" rel="lightbox"><img class="alignnone size-full wp-image-9591" title="infinitest1" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/infinitest12.png" alt="" width="640" height="243" /></a></p>
<p>The problem indicator is quite powerful and allows a higher level of TDD. When doing pure TDD you write a failing test first. This would make Infinitest mark your assert statement as problematic until you save a working implementation of your tested code. This allows a very focused <em>write failing test / write implementation</em>-loop.</p>
<p>Infinitest operates independently from the JUnit view in Eclipse. As Infinitest is activated as soon as source code is saved while JUnit is run when initiated by the developer the state shown by either system is often out of sync. I have also experienced that the Infinitest fails to "re-test" but then a project clean brings it back on track. Even if there are quirks I think Infinitest is useful for my daily work and it really promotes TDD.</p>
<p>The plug-in is available on update site http://infinitest.github.com/ and if you are using SpringSource Tool Suite (STS) the plug-in is also available in STS's  extension list.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/21/infinitest/feed/</wfw:commentRss>
		<slash:comments>1</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>Sync-Async Pair Pattern &#8211; Easy concurrency on iOS</title>
		<link>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/</link>
		<comments>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 09:10:19 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8208</guid>
		<description><![CDATA[Apple provides many tools for implementing concurrency in your application. NSOperationQueue, GCD, or simply using performSelectorInBackground:withObject: that is available on each and every object, are just some examples. The tools are there, yet implementing good concurrency is hard. The solution I have found is not yet another tool, or framework, but a simple pattern. I [...]]]></description>
			<content:encoded><![CDATA[<p>Apple provides many tools for implementing concurrency in your application. <code>NSOperationQueue</code>, GCD, or simply using <code>performSelectorInBackground:withObject:</code> that is available on each and every object, are just some examples. The tools are there, yet implementing good concurrency is hard.</p>
<p>The solution I have found is not yet another tool, or framework, but a simple pattern. I have not found an existing name for the pattern so I call it Sync-Async Pair. The idea is to hide the complexity of asynchronous calls and call-back behind a facade, and have a straightforward synchronous implementation. An implementation that is easy to write, test and extend.</p>
<h3>Sync-Async Pair Pattern</h3>
<p>As the name suggests the pattern consist of a method pair, one is synchronous, and the other is asynchronous. The asynchronous method is backed by the synchronous implementation, and is only responsible for erecting a simplified facade in front of the sometimes complex concurrent implementation. </p>
<p>The first priority is to expose a clean API, the second priority is an implementation that is simple, testable and maintainable. Turns out that beginning with a clean API design (how to use the code), steers you towards a clean implementation (how to write the code). Most developers do the mistake to first write the code, and then struggle to try to use their own code.</p>
<p>Sync-Asyn Pair begins by defining a public API that then steers towards a clean implementation. Let's assume we are implementing some kind of a book reader. We need two model objects; <code>CWBook</code> and <code>CWChapter</code>. Both books and chapters are fetched from the network, so we need concurrency in order to not block the UI thread.</p>
<p>For this example let's focus only on fetching the chapters associated with a book. All other operations would be implemented in a similar fashion. First we need a public API, two methods for the sync-async pair on <code>CWBook</code>, and a delegate protocol.</p>
<pre class="brush:objc">@protocol CWBookFetchChaptersDelegate &lt;NSObject&gt;
-(void)bookDidFetchChapters:(CWBook*)book;
-(void)book:(CWBook*)book failedFetchChaptersWithError:(NSError*)error;
@end
// ...
-(BOOL)fetchChaptersWithError:(NSError**)error;
-(void)fetchChaptersWithAsyncDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
</pre>
<p>The synchronous method <code>fetchChaptersWithError:</code> is very straightforward to implement.</p>
<pre class="brush:objc">-(BOOL)fetchChaptersWithError:(NSError**)error;
{
    NSURL* url = [self URLForFetchingChapters];
    NSData* data = [NSData dataWithContentsOfURL:url
                                         options:0
                                           error:error];
    if (data) {
        return [self parseChaptersFromData:data
                                     error:error];
    }
    return NO;
}</pre>
<p>How to construct the <code>NSURL</code>, or possibly <code>NSURLRequest</code> is not important. Nor is it important how you actually parse the resulting data sent from the server, that is totally left to our problem domain. Just make it synchronous and super easy to write automatic unit checks for!</p>
<h3>Adding Concurrency</h3>
<p>Now to the hard part, that is actually quite manageable; adding the concurrency. For this example I will use <code>performSelectorInBackground:withObject:</code>. Your specific implementation might need <code>NSOperationQueue</code>, or GCD if you have special needs such as queues or cancelable operations. The idea will remain the same.</p>
<p>The most basic, and common, implementation for the public async method simply fires off the concurrent operation:</p>
<pre class="brush:objc">-(void)fetchChaptersWithAsyncDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    [self performSelectorInBackground:@selector(fetchChaptersWithDelegate:)
                           withObject:delegate];
}</pre>
<p>In most cases all it does is request a private method to be performed on a background thread at some point in time. This is also the perfect place to abort operations early, for example a no-op if a request such as fetching a thumbnail is already in progress.</p>
<p>The private method previously launched is where most of the work is done. This is where a <code>NSAutoreleasePool</code> is setup, the synchronous method is called, and the delegate is properly called on the proper thread. The basic implementation for fetching books would be:</p>
<pre class="brush:objc">-(void)fetchChaptersWithDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSError* error = nil;
    BOOL success = [self fetchChaptersWithError:&error];
    if (success) {
        [[NSInvocation invocationWithTarget:delegate
                                   selector:@selector(bookDidFetchChapters:)
                            retainArguments:YES, self] invokeOnMainThreadWaitUntilDone:NO];
    } else {
        [[NSInvocation invocationWithTarget:delegate
                                   selector:@selector(book:failedFetchChaptersWithError:)
                            retainArguments:YES, self, error] invokeOnMainThreadWaitUntilDone:NO];
    }
    [pool release];
}</pre>
<p>For this example I am using my <code>NSInvocation</code> additions to perform the delegate callbacks to the main thread, but it could just as easily been done using GCD. The additions are described in detail and available for download in <a href="http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/">this blog post</a>, or from in the <a href="https://github.com/jayway/CWFoundation">CWFoundation repo on github</a>.</p>
<p>As you can see the boiler plate code for managing concurrency is actually very minimal, much less than 10 statements in total. The boilerplate code is almost reduced to only calling other methods, leaving very very few opportunities for bugs to sneak in.</p>
<h3>Core Data in the Mix</h3>
<p>The Sync-Async Pair pattern also lend itself beautifully for writing multi-threaded Core Data. The hassle of juggling <code>NSManagedObjectID</code> and <code>NSManagedObject</code> instances from different contexts can be completely left up to the private implementation that calls the synchronous method.</p>
<p>The private method responsible for calling the synchronous method and handling callbacks could be implemented as such:</p>
<pre class="brush:objc">-(void)notifyDelegate:(id)delegate ofSuccess:(BOOL)success withError:(NSError*)error;
{
    self = [[NSManagedObjectContext threadLocalContext] objectWithID:[self objectID]];
    if (success) {
        [delegate bookDidFetchChapters:self];
    } else {
        [delegate book:self failedFetchChaptersWithError:error];
    }
}

-(void)fetchChaptersWithDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    self = [[NSManagedObjectContext threadLocalContext] objectWithID:[self objectID]];
    NSError* error = nil;
    BOOL success = [self fetchChaptersWithError:&error];
    [[NSInvocation invocationWithTarget:self
                               selector:@selector(notifyDelegate:ofSuccess:withError:)
                        retainArguments:YES, delegate, success, error] invokeOnMainThreadWaitUntilDone:NO];
    [pool release];
}</pre>
<p>Not much extra code, and the ugliness of handling Core Data's managed contexts is neatly hidden for clients at a single point in the code, that is much easier to test, debug, and maintain than most conventional Core Data code.</p>
<h3>Conclusions</h3>
<p>The simple Sync-Async Pair pattern makes it easy to write robust concurrent code. It is even a pattern that by design yields an elegant public API. It is also very easy to test, extend and even change the internal implementation completely without affecting any clients.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Cucumber tests on iPhone/iPad</title>
		<link>http://blog.jayway.com/2011/02/11/cucumber-tests-on-iphoneipad/</link>
		<comments>http://blog.jayway.com/2011/02/11/cucumber-tests-on-iphoneipad/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 10:18:18 +0000</pubDate>
		<dc:creator>Davor Crnomat</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7129</guid>
		<description><![CDATA[I am sure everybody has heard about Cucumber ( https://github.com/aslakhellesoy/cucumber) – a tool for Behaviour Driver Development where you describe software behavior in natural language that your customer can understand. Through step definitions these behavior descriptions are executed as automated tests. Cucumber serves as documentation, automated tests and development aid. My friend and colleague Christian [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">I am sure everybody has heard about Cucumber ( </span></span></span><span style="color: #000071;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><span style="text-decoration: underline;">https://github.com/aslakhellesoy/cucumber</span></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">) – a tool for Behaviour Driver Development where you describe software behavior in natural language that your customer can understand. Through step definitions these behavior descriptions are executed as automated tests. Cucumber serves as documentation, automated tests and development aid.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">My friend and colleague Christian Hedin gave me tips on iCuke. Cucumber has been widely used for testing web applications, but now it’s also possible to test iOS (iPhone and iPad) apps with help of the iCuke library (</span></span></span><span style="color: #000071;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><span style="text-decoration: underline;">https://github.com/unboxed/icuke</span></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">). iCuke uses AppleScript to drive XCode in order to launch your application into the iOS Simulator. A preloaded library is used to inject a small HTTP server into your application. The HTTP server allows you to see an XML representation of the iOS device screen and to emulate input, such as taps, swipes and pinch gestures.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">You can read more about it here:<br />
</span></span></span><span style="font-family: 'Times New Roman', serif; font-size: small; color: #000071;"><span style="text-decoration: underline;">http://www.unboxedconsulting.com/blog/cucumber-iphone-icuke<br />
</span></span><span style="font-family: 'Times New Roman', serif; font-size: small; color: #000071;"><span style="text-decoration: underline;">http://pragprog.com/magazines/2010-07/bdd-on-iphone-icuke</span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Really excited about Cucumber on iPhone we decided to give it a try. After installing iCuke and doing some test runs it was clear that some challenges had to be overcome to make this a truly useful tool for Behaviour Driven Development and automated testing of iOS apps.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Challenge 1: Screen returns the previous screen's xml</strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In our test, we wanted to tap a button, come to another screen and expected to see a text. When the test runs the iPhone is driven to the correct screen, e can see the expected text but the test fails anyway. After little debugging we realized that the method </span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><em>screen.xml</em></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"> returns old xml directly after changing the screen.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Solution: </strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">We needed to refresh screen before checking if the expected text is on the new screen. iCuke has a method to refresh screen but it is private and we could not use it. So we just added a new method to the existing ICukeWorld class.</span></span></span></p>
<pre class="code"><span style="color: #500000;"><span style="font-size: x-small;"><strong>class</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> ICukeWorld</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>def</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> refresh_screen</span></span>
<span style="color: #000000;">   <span style="font-size: x-small;">refresh</span></span>
<span style="color: #000000;">   <span style="font-size: x-small;">screen</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Calling this method before checking for the presence of the text solved this problem. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Later on, I forked iCuke and added this and some other methods.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Courier New';"><span style="font-size: small;">git://github.com/DavorC/icuke.git</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Challenge 2: Timing</strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Everybody knows that using sleep and delays in code is not so flexible.</span></span></span></p>
<pre class="ruby"><span style="color: #210000;"><span style="font-size: x-small;">sleep</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">3</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #444444;"><span style="font-size: x-small;"># wait 3 seconds</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">We want to check something on the screen and give it 3 seconds to finish its loading. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Is it enough? Maybe, maybe not. Screen content loading could take 0.1 second or 5 seconds or... - You know what I mean. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In the first case loading is finished quickly and we unnecessarily spend 3 seconds for doing nothing . If we have a lot of delays in our code then our tests would waste a lot of precious time. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In the second case the delay is not long enough and the test fails.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Solution:</strong></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"> </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">We need to write some help functions to wait for different items which are expected: some text, a button, downloading spinner etc.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Example with wait for text:</span></span></span></p>
<pre class="ruby"><span style="color: #500000;"><span style="font-size: x-small;"><strong>def</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> wait_for_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"#{method_name}(#{text}, #{timeout})"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@debug</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">refresh_screen</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">start_time </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> Time</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">now</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>until</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">screen</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">))</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>   if</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> Time</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">now </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">-</span></span><span style="color: #000000;"><span style="font-size: x-small;"> start_time &gt; timeout</span></span>
<span style="color: #000000;">     <span style="font-size: x-small;">flunk</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"#{method_name}: Timed out after #{timeout} seconds"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;">   </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">sleep</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #215f00;"><span style="font-size: x-small;">0.1</span></span>
<span style="color: #000000;">   <span style="font-size: x-small;">refresh_screen</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">As you can see the method is waiting for the text to appear and does checking every 0.1 second. As soon as the text is found the test continues. If, after given timeout, the text is still not found, the test fails.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">I prefer to use unit test assertions in my tests (</span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><em>flunk</em></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"> is an assert which always fails). To use assertions with cucumber you need to add assertions to the Cucumber World:</span></span></span></p>
<pre class="ruby"><span style="color: #210000;"><span style="font-size: x-small;">require</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'test/unit/assertions'</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">World</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">Test::Unit::Assertions</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Challenge 3: </strong></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"> </span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Different tappable object on screen can have the same text label.</strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Identifying objects on the screen only by text is not enough.</span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong> </strong></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">By default, the first tappable object is tapped. What if we want to tap the second one?</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Solution:</strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">I created a set of help functions for: </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">returning all objects that satisfy some criteria</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">returning a specific object</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">waiting for a specific object</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">checking if a specific object exists</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Objects are described in xml by: type, label, traits and index.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Here is an example of getting an array of all elements satisfying given attribute values.</span></span></span></p>
<pre class="ruby"><span style="color: #500000;"><span style="font-size: x-small;"><strong>def</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> get_all_elements_by_type_label_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"#{method_name}(#{type}, #{label}, #{traits})"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@debug</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">refresh_screen</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">doc </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> REXML::Document</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>new</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">screen</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">xml</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">to_s</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">elements </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> REXML::XPath</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">match</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">doc, </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"//#{type}[@label=#{label.inspect}][@traits=#{traits.inspect}]"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">elements</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Observe how it is easy to parse xml using ruby's REXML library.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Of course I could write more generic methods and decrease number of code lines - something like: </span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;">get_all_elements</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, options </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #4f005f;"><span style="font-size: x-small;">{}</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">but I like readability so I wrote a set of help functions with more specific naming:</span></span></span></p>
<p><span style="color: #000000;"><span style="font-size: x-small;">get_element_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)<br />
</span></span><span style="font-size: 13.2px;"><span style="color: #000000;"><span style="font-size: x-small;">get_element_by_type_and_label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)<br />
</span></span></span><span style="font-size: 13.2px;"><span style="color: #000000;"><span style="font-size: x-small;">get_element_by_type_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_element_by_type_label_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_elements_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_elements_by_type_and_label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_elements_by_type_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_elements_by_type_label_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_static_texts</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">()</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_labels_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_labels_by_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">element_by_type_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">element_by_type_and_label_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">element_by_type_and_traits_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">element_by_type_label_and_traits_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">text_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_element_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_element_by_type_and_label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_element_by_type_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_element_by_type_label_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_center_of_the_element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">tap_coordinates</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">x, y</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">double_tap_coordinates</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">x, y</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">tap_element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">double_tap_element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">tap_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">double_tap_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In order to use these functions you need to use iCuke from:</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Courier New';"><span style="font-size: small;">git://github.com/DavorC/icuke.git</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Don't forget to use –recursive flag when you clone it:</span></span></span></p>
<pre><span style="color: #000000;"><span style="font-family: 'Courier New';"><span style="font-size: small;">git clone --recursive git://github.com/DavorC/icuke.git</span></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">After building and installing the iCuke gem you need to </span></span></span></p>
<pre><span style="color: #210000;"><span style="font-size: x-small;">require</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'icuke/cucumber_ext'</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">instead of:</span></span></span></p>
<pre><span style="color: #210000;"><span style="font-size: x-small;">require</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'icuke/cucumber'</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: Arial, sans-serif;"><span style="font-size: medium;">Example of usage</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In your feature-file:</span></span></span></p>
<pre><span style="color: #000000;"><span style="font-size: x-small;">Background:</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">Given </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"myApp.xcodeproj"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> is loaded </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>in</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> the simulator</span></span>

<span style="color: #000000;"><span style="font-size: x-small;">Scenario Outline: User try to login with different invalid credentials with valid signs</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">When I am in </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Account"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> section</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;"> And I paste in username </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"&lt;user&gt;"</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;"> And I paste in password </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"&lt;pass&gt;"</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;"> And I tap Login button</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">Then I will see alert dialog</span></span>

<span style="color: #000000;"> <span style="font-size: x-small;">Examples:</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">| user            | pass      |</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">| </span></span><span style="color: #210000;"><span style="font-size: x-small;">test</span></span><span style="color: #000000;"><span style="font-size: x-small;">@</span></span><span style="color: #210000;"><span style="font-size: x-small;">test</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">com   | </span></span><span style="color: #210000;"><span style="font-size: x-small;">test</span></span><span style="color: #000000;"><span style="font-size: x-small;">      |</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">| 123456          | qwertyui  |</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">| </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">..</span></span><span style="color: #000000;"><span style="font-size: x-small;">@</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">..</span></span><span style="color: #000000;"><span style="font-size: x-small;">com        | </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;"> €&lt;&gt; |</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">step definitions:</span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;">When </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;">I am </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>in</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"(.*)"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> section</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> |section|</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">wait_for_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">section</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">tap</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">section</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">wait_for_element_by_type_and_label</span></span></span><span style="color: #6d6e1d;"><span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">(</span></span></span><span style="color: #0400e6;"><span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">"UINavigationItemView"</span></span></span><span style="color: #000000;"><span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">, section</span></span></span><span style="color: #6d6e1d;"><span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">)</span></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>

<span style="color: #000000;"><span style="font-size: x-small;">When </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;">I paste </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>in</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> username </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"(.*)"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> |user|</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">label </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"E-mail"</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">refresh_screen</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">assert</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">get_all_static_texts</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">().</span></span><span style="color: #000000;"><span style="font-size: x-small;">include?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><span style="color: #000000;"><span style="font-size: x-small;">, </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"No text field with label #{label} was found"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">write_to_mac_clipboard</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">user</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">paste_clipboard_to_text_field</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"UITextFieldLabel"</span></span><span style="color: #000000;"><span style="font-size: x-small;">, label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>

<span style="color: #000000;"><span style="font-size: x-small;">When </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"I tap Login button"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">wait_for_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Login"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">tap</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Login"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #5a5c00;"> </span><span style="color: #000000;"><span style="font-size: x-small;">wait_for_download_indicator_finish</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>

<span style="color: #000000;"><span style="font-size: x-small;">Then </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"I will see alert dialog"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">wait_for_element_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"UIAlertView"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: Arial, sans-serif;"><span style="font-size: medium;">Testing both iPhone and iPad</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">If you’re testing a universal app that runs on both iPhone and iPad I recommend writing different scenarios for the platforms. iPad in landscape mode is most likely to reuse most of code you have written for iPhone. Place them in different feature files and tag them with e.g. @iphone respective @ipad tags.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In your env.rb file:</span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;">$PLATFORM </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"iphone"</span></span>

<span style="color: #000000;"><span style="font-size: x-small;">Before</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'@ipad'</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">$PLATFORM </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"ipad"</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>

<span style="color: #000000;"><span style="font-size: x-small;">Before</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'@iphone'</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">$PLATFORM </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"iphone"</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Use in your feature files:</span></span></span></p>
<pre><span style="color: #000000;"><span style="font-size: small;">Given I have started application</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Implementation:</span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;"><strong>Given </strong></span></span><span style="color: #0000ea;"><span style="font-size: x-small;"><strong>"I have started the application"</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"><strong> </strong></span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> </span><span style="color: #444444;"><span style="font-size: x-small;"># ... some code</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">Given </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"\"</span></span><span style="color: #000000;"><span style="font-size: x-small;">myApp\</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">" from \"</span></span><span style="color: #000000;"><span style="font-size: x-small;">myApp</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">xcodeproj\</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">" is loaded in the #{$PLATFORM} simulator"</span></span>
<span style="color: #000000;"> </span><span style="color: #444444;"><span style="font-size: x-small;"># ... more code</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">If you wants to run iPad simulator in landscape mode:</span></span></span></p>
<pre class="ruby"><span style="color: #500000;"><span style="font-size: x-small;"><strong>def</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> switch_ipad_to_landscape</span></span>
<span style="color: #500000;"> <span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">get_ipad_orientation </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">==</span></span><span style="color: #000000;"><span style="font-size: x-small;"> PORTRAIT</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;">   <span style="font-size: x-small;">rotate_simulator_left</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">where</span></span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong> </strong></span></span><span style="color: #000000;"><span style="font-size: x-small;">get_ipad_orientation </span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">is some application specific method to decide if the simulator is in portrait or landscape mode.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: Arial, sans-serif;"><span style="font-size: medium;">Running iCuke tests on Hudson server</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">It’s really nice to be able to run your test suite at given intervals, or when you commit to the source code repository. To run your iCuke tests on Hudson (which is a popular continuous integration build server) you must start your iPhone simulator from a terminal window. This is easiest to do by launching an AppleScript from Hudson. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Below are two scripts, one AppleScript and one shell script, that I used to run my iCuke tests from Hudson. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">- run_cuke.scpt</span></span></span></p>
<pre><span style="color: #5a5c00;"><span style="font-size: x-small;">--</span></span><span style="color: #000000;"><span style="font-size: x-small;"> run_cuke.scpt</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>tell</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> application </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Finder"</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> my_folder_path to container of </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">path to me</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><span style="color: #000000;"><span style="font-size: x-small;"> as </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>text</strong></span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> posixPath to POSIX path of </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>file</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> my_folder_path</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> scriptPath to posixPath </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"cuke.sh"</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">end </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>tell</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>tell</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> application </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Terminal"</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">activate</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">do script scriptPath</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">end </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>tell</strong></span></span>
<span style="color: #000000;"><span style="font-size: x-small;">delay </span></span><span style="color: #246b00;"><span style="font-size: x-small;">1200</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">--</span></span><span style="color: #000000;"><span style="font-size: x-small;"> it should be enough to finish all tests</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> logscript to </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"grep -c FAILED "</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> posixPath </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"cuke.log"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">" | cat"</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> cuke_failed to do shell script logscript</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> cuke_failed </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;"> then</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>error</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Cucumber tests failed"</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">end </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>if</strong></span></span>
<span style="color: #000000;"><span style="font-size: x-small;">try </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">--</span></span><span style="color: #000000;"><span style="font-size: x-small;"> do not leave terminals </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>after</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> test run</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">do shell script </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"killall 'Terminal'"</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">end try</span></span></pre>
<p><span style="color: #000000;"><span style="font-size: x-small;">- cuke.sh</span></span></p>
<pre><span style="color: #444444;"><span style="font-size: x-small;">#!/bin/bash</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">scriptpath</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;">$</span></span><span style="color: #4f005f;"><span style="font-size: x-small;">(</span></span><span style="color: #92504f;"><span style="font-size: x-small;"><strong>cd</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> ${</span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">%</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">*</span></span><span style="color: #000000;"><span style="font-size: x-small;">} </span></span><span style="color: #4f005f;"><span style="font-size: x-small;">&amp;&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #92504f;"><span style="font-size: x-small;"><strong>echo</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> $PWD</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;">${</span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #444444;"><span style="font-size: x-small;">##*/})</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">SCRIPTFOLDER</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;">`dirname </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"$scriptpath"</span></span><span style="color: #000000;"><span style="font-size: x-small;">`</span></span>
<span style="color: #92504f;"><span style="font-size: x-small;"><strong>echo</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> Cucumber script is run </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>in</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">:</span></span><span style="color: #000000;"><span style="font-size: x-small;"> $SCRIPTFOLDER</span></span>
<span style="color: #92504f;"><span style="font-size: x-small;"><strong>cd</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> $SCRIPTFOLDER</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">cucumber $SCRIPTFOLDER</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/features</span></span><span style="color: #000000;"><span style="font-size: x-small;"> --format</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;">html --out $SCRIPTFOLDER</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/cuke_results</span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>.</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;">html </span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> $SCRIPTFOLDER</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/cuke</span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>.</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;">log</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Add these two scripts to your project.</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Then, add this Cucumber hook to your env.rb file:</span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;">After </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> |s|</span></span>
<span style="color: #500000;"> <span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">s</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">failed?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Scenario FAILED: &lt;#{s.name}&gt;"</span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"More info about failure: SCREEN XML"</span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> screen</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">xml</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>else</strong></span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Scenario PASS: &lt;#{s.name}&gt;"</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">On Hudson, create a new job and copy the configuration from your project's existing job.</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Configure job: </span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">add to description:</span></span></span></p>
<pre><span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">a href</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/hudson/job/Helios_Cuke/ws/cuke_results</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">.html"</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">Cucumber Results</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/a</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span>
<span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">b</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">|</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/b</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span>
<span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">a href</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/hudson/job/Helios_Cuke/ws/cuke</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">.log"</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">Debug</span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>.</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;">log</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/a</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">add build step (execute shell):</span></span></span></p>
<pre><span style="color: #000000;"><span style="font-size: x-small;">osascript ${WORKSPACE}/run_cuke.scpt</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Of course you can change all scripts according your needs.</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">At the end you should have your iCuke tests running on Hudson and you will get both a nice test report in HTML and the debug output as a plain text.</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">There is a lot of potential for doing automated feature tests for iOS using Cucumber and with iCuke and the additions above you’ll hopefully be well on your way for doing BDD in your next iOS project!</span></span></span><br />
<script src="js/shCore.js">// <![CDATA[
  mce:0
// ]]&gt;</script> <script src="js/shBrushCSharp.js">// <![CDATA[
  mce:1
// ]]&gt;</script><br />
<script src="js/shBrushXml.js">// <![CDATA[
  mce:2
// ]]&gt;</script> <script type="text/javascript">// <![CDATA[
  mce:3
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/02/11/cucumber-tests-on-iphoneipad/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Automated Testing is Like Optimizing</title>
		<link>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/</link>
		<comments>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 09:57:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=4624</guid>
		<description><![CDATA[Continuos Integration is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://martinfowler.com/articles/continuousIntegration.html" title="Continuous Integration">Continuos Integration</a> is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you and your team will be notified right away.
</p>
<p>
This is the second part of the blog post I wrote about <a href="http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/">TDD in XCode</a>. Make sure you've followed that tutorial before continuing here, or at least have a project of your own with OCUnit tests ready.
</p>
<p>
The server which we'll use is called <a href="https://hudson.dev.java.net/" title="Hudson">Hudson</a> and is very popular in the Java community. It does not readily support XCode projects but it does allow shell commands, so we'll use that to make our Calculator project compatible. We also want to fetch new versions of the source code as soon as it's checked in. We'll be a bit fancy and use <a href="http://git-scm.com/" title="Git - Fast Version Control System">Git</a> as source control software.	Here's a summary of what we want to do:
</p>
<ol>
<li>Download and install the Hudson continuos integration server</li>
<li>Download, install and setup the Git source control software as well as the Git plugin for Hudson</li>
<li>Download and install a script that converts OCUnit test results to JUnit format</li>
<li>Setup a new job in Hudson that checks out our XCode project and builds and tests it</li>
<li>Set up a notification and try it out</li>
</ol>
<h2>Downloading and Installing Hudson</h2>
<p>
In order to keep the instructions in this tutorial simple, we will have the source code repository and the build server itself on localhost. In real life you'll probably want to setup a dedicated machine.</p>
<p>Head over to the <a href="https://hudson.dev.java.net/" title="Hudson">Hudson web site</a> and download your copy of the server. Follow their included installation instructions, it's quite simple. Once you have Hudson up and running you can visit <a href="http://localhots:8080">http://localhost:8080</a> to see the welcome screen. By the way, when you're ready to install Hudson on a real remote server I recommend running it as a Servlet inside <a href="http://tomcat.apache.org/" title="Apache Tomcat - Welcome!">Apache Tomcat</a> instead.
</p>
<h2>Downloading and Setting Up Git</h2>
<p>Next we want to install Git. There are several ways to install it. The simplest might be to use <a href="http://code.google.com/p/git-osx-installer/">the OS X installer</a>, but I personally prefer <a href="http://www.macports.org/" title="The MacPorts Project">MacPorts</a>. Either way, go ahead and install it and make sure that you can use the "git" command from Terminal.app when you're done.
</p>
<p>
In the Terminal, change directory to your XCode project folder and type:</p>
<pre class="brush:bash">
		git init
	</pre>
<p>You now have a working source code repository in your project folder. Neat. Before you continue create a text file called <em>.gitignore</em> and let it contain:</p>
<pre class="brush:plain">
		build/*
		*.pbxuser
		*.mode1v3
		.DS_Store
		test-reports/*
	</pre>
<p>	That's a listing of the files and folders that should not be version controlled, since they are temporary or just used for XCode. Feel free to add any other files that you think only should be present locally. Now add all files (that aren't ignored) using:</p>
<pre class="brush:bash">
		git add *
	</pre>
<p>	and finally commit them to a first version using:</p>
<pre class="brush:bash">
		git commit -m "Initial import"
	</pre>
</p>
<h2>Fetching the Script</h2>
<p>
We need to fetch one more thing, <a href="http://github.com/ciryon/OCUnit2JUnit/blob/master/ocunit2junit.rb">ocunit2junit.rb</a>, which is a little Ruby script that I wrote. Since you now have git, you can also download it using git (or <em>clone the repo</em>, which is the correct term). Change directory to /tmp and then type like this:</p>
<pre class="brush:bash">git clone git://github.com/ciryon/OCUnit2JUnit.git</pre>
<p>Copy the script from /tmp/OCUnit2JUnit/ anywhere, like to /usr/local/bin/. Make sure it's executable by typing <em>chmod +x ocunit2junit.rb</em>.</p>
<p>The script will parse output from xcodebuild (the console command for building your XCode project) and look for output from OCUnit. The test results (success, failure, time passed etc) will be saved in the "test-reports" folder in the same XML format that JUnit uses. This also happens to be a format that Hudson understands.
</p>
<h2>Setting Up Hudson</h2>
<p>
Now head back to your Hudson welcome screen. Select <em>Manage Hudson</em>, <em>Manage plugins</em> and check "Hudson GIT plugin" under <em>Available</em>. Hudson will automatically download and install the plugin. Afterwards just restart Hudson.
</p>
<p>
We're ready to create a job in Hudson for our project. From the main screen select "New job", Build a free-style software project and call it "Calculator". There are some settings which you should fill in:</p>
<ul>
<li>
			Select to use git as source code management tool. The URL should be the file path to your project, like:
<pre class="brush:bash">/Users/youruser/XCodeProjects/Calculator/</pre>
</li>
<li>
			Select to poll SCM with Schedule:
<pre class="brush:bash">* * * * *</pre>
<p>			That means it'll check every minute if there are changes. If you want to check less often, do that.
		</li>
<li>
			Add new build step and select to execute shell. Use this command (make sure to point to the version of the iPhone SDK you want to use):</p>
<pre class="brush:plain">xcodebuild -target "UnitTests" -sdk /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.2.sdk/ -configuration "Debug" | /usr/local/bin/ocunit2junit.rb</pre>
</li>
<li>
			Select to also publish a JUnit test result report and the Test report XMLs reside at
<pre class="brush:plain">test-reports/*.xml</pre>
</li>
</ul>
<h2>Trying it out</h2>
<p>This is the moment of truth. Try to change your CalculatorTest.m so that one of the test cases fail. Type:</p>
<pre class="brush:bash">
	git -a commit CalculatorTest.m "Broke the test, on purpose"
</pre>
<p>and see what happens. If all goes well, and you have entered everything correctly,  Hudson should automatically notice there's a new version available, build it and try to run the test suite. Check the results and how it reports the test failure. Nice, eh? Fix the error and commit the test class again to see how Hudson reacts.
</p>
<p>
There are many settings, plugins and cool things to try out in Hudson. Go into Manage Hudson-> Configure system and setup your email settings, to allow Hudson to send mail. Then go back to configure your Calculator job and at the bottom select E-mail Notification. Enter your own email address and see how it works after you commits a file that breaks the build. If you don't want a mail, you can get an instant message, or perhaps have the server play a loud annoying sound? Everyone in your team should be aware of when a build fails, so it can be fixed right away. This is one of the great advantages of having a continuos integration server.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>The easy way to test Android applications</title>
		<link>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/</link>
		<comments>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 09:44:44 +0000</pubDate>
		<dc:creator>Renas Reda</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4536</guid>
		<description><![CDATA[I’m going to guess that most of you know what instrumentation is. In the event that you don't, instrumentation is a feature in which specific monitoring of the interactions between an application and the system is made possible. Instrumentation also makes it possible to write test cases that interact with the application. The problem with [...]]]></description>
			<content:encoded><![CDATA[<p>I’m going to guess that most of you know what instrumentation is. In the event that you don't, instrumentation is a feature in which specific monitoring of the interactions between an application and the system is made possible. Instrumentation also makes it possible to write test cases that interact with the application. The problem with instrumentation, however, is that it is incredibly hard to write solid test cases for applications bigger than the typical “Hello World!” application. A tremendous amount of technical details must be taken into account in order to write a good test case. Often, developers quickly realize that it will take almost as long to write a comprehensive test case as it took to write the whole application. I, myself, came to recognize the very same thing when I first started looking into how to use instrumentation tests with the android application project that I’m currently working on.</p>
<p>I soon came to understand that I would not be able to take advantage of all the wonderful possibilities that instrumentation offers. The reason for that is quite simple; the application that we are in the process of developing is not only extensive but also complicated with multiple activities, self-defined intents, and hundreds of views that also include scrollable lists. It would not make sense for me to spend a month writing one single test case that would only take 20 seconds to test manually. That is how Robotium was born. I needed a test framework that would help me write good and powerful test cases that emulated real users. The test case should be able to do what a real user does: click on anything that is clickable, look for irregularities, automatically move from activity to activity, etc. More importantly, I should not have to spend more than 10 minutes writing a test case that involves more then one activity.</p>
<p>With the help of Robotium a test case spanning over multiple activities could look like this:</p>
<pre class="brush:java">public void testTextIsSaved() throws Exception {
   solo.clickOnText("Other");
   solo.clickOnButton("Edit");
   assertTrue(solo.searchText("Edit Window"));
   solo.enterText(0, "Some text for testing purposes")
   solo.clickOnButton("Save");
   assertTrue(solo.searchText("Changes have been made successfully"));
   solo.clickOnButton("Ok");
   assertTrue(solo.searchText("Some text for testing purposes"));
}
</pre>
<p>As you can see, I don’t have to specify any technical details or tell Robotium where to look for something, such as scrolling down a list when needed. It handles the above and more all on its own.</p>
<p>If you are interested in writing test cases of similar nature have a look at http://www.robotium.org. It makes writing powerful test cases a breeze.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/feed/</wfw:commentRss>
		<slash:comments>20</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>Running Selenium RC with Firefox 3</title>
		<link>http://blog.jayway.com/2008/11/12/running-selenium-rc-with-firefox-3/</link>
		<comments>http://blog.jayway.com/2008/11/12/running-selenium-rc-with-firefox-3/#comments</comments>
		<pubDate>Wed, 12 Nov 2008 11:22:46 +0000</pubDate>
		<dc:creator>Joakim Back</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[firefox 3]]></category>
		<category><![CDATA[selenium]]></category>
		<category><![CDATA[ubuntu]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=393</guid>
		<description><![CDATA[After running into proxy errors attempting to run Selenium tests with Opera 9.62 and being unable to install Firefox 2 on Ubuntu 8.10 (unsatisfied package dependencies..) I finally ran into this gem: Hi, On windows I succeeded to run Selenium RC and Firefox 3 using the following steps 1. run firefox in profilemanager mode ("path\to\firefox.exe" [...]]]></description>
			<content:encoded><![CDATA[<p>After running into proxy errors attempting to run Selenium tests with Opera 9.62 and being unable to install Firefox 2 on Ubuntu 8.10 (unsatisfied package dependencies..) I finally ran into <a href="http://clearspace.openqa.org/message/48380#48380">this gem</a>:</p>
<p><em>Hi,</em><br />
<em><br />
On windows I succeeded to run Selenium RC and Firefox 3 using the following steps</em></p>
<p><em>1. run firefox in profilemanager mode ("path\to\firefox.exe" -profilemanager)<br />
2. create new profile (e.g. selenese) with a specific path (e.g.a directory in your workspace)<br />
3. open this new profile from within the profile manager and change the proxy settings within firefox (localhost:4444 or change accordingly in case your selenium RC server runs on a different port)<br />
4. use the following browser string within Selenium RC: *custom path\to\firefox.exe -no-remote -profile path\to\profile\selenese</em></p>
<p>I had to enable popups for the profile, but other than that.. the solution seems to work fine on ubuntu as well!</p>
<p>Edit: <a href="http://notetodogself.blogspot.com/2008/10/use-selenium-rc-in-firefox-3.html">Here's a different work-around</a>. I haven't tried it, but it does have the benefit of a generic browser path.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/12/running-selenium-rc-with-firefox-3/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Testing Among the Clouds, Part 2</title>
		<link>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/</link>
		<comments>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 14:22:56 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[typica]]></category>

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

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=3445</guid>
		<description><![CDATA[Mock objects is a very useful technique for unit testing as it allows you to focus your testing efforts on the class being tested instead of on its collaborators. Unfortunately, not everything is an object and therefore you cannot always use mock objects. This article will show how mocking can be generalized to include more [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Mock objects is a very useful technique for unit testing as it allows you to focus your testing efforts on the class being tested instead of on its collaborators. Unfortunately, not everything is an object and therefore you cannot always use mock objects. This article will show how mocking can be generalized to include more things than just objects. </strong></p>
<h2>Motivation</h2>
<p>When unit testing we would like to test only a single unit of code without any exter-<br />
nal dependencies. However, an object seldom lives in isolation and often has one or<br />
more collaborators, which it communicates with using method calls. Mock objects<br />
is a well known technique (1) that that can be used to simulate the collaborators<br />
and thereby create a totally controlled environment. Mock objects together with<br />
test driven development is also very useful for improving the design as you discover<br />
how your class should be used.<br />
So everything is fine? Well, not everything is an object, even in Java. Sometimes<br />
static methods are used and it is no longer possible to use the mock object technique<br />
as there no longer is an object. But that has a simple solution: “Don’t use static<br />
methods” - right? Sure, if you write all code yourself that is possible, but almost all<br />
projects have external dependencies outside of the project’s control. It is even worse<br />
than you might initially think as Java standard APIs often have lots of static methods.<br />
Some examples: </p>
<pre>
•Java	SE:	System.getProperty(String name)
•Java	ME:	RecordStore.openRecordStore(String recordStoreName,
                boolean	createIfNecessary) 
</pre>
<h2>Example </h2>
<p>In the last issue of JayView there was an article about a tool called MockME that<br />
makes it possible to mock the static methods that are abundant in the Java ME<br />
APIs (2). This article tries to solve this problem in a more general way.<br />
Let us use the same code example which uses the RecordStore from Java ME and<br />
examine	the	problem	again.	For	those	of	you	unfamiliar	with	Java	ME,	RecordStore<br />
is an API for storing byte array records persistently on the phone. </p>
<pre>public class RecordStore {
  public static RecordStore openRecordStore(String recordStoreName,
                                            boolean createIfNecessary)
      throws RecordStoreException,
             RecordStoreFullException,
             RecordStoreNotFoundException {
    // implementation goes here
  }
    // ...
}</pre>
<p>We now implement a data access object (DAO) that we use to store messages.<br />
It will allow us to store and access messages from a RecordStore without bothering<br />
with the details how the message is stored. </p>
<pre>public class MessageDao {
  private static final String RECORD_STORE_NAME = “MessageDao”; 

  public void addMessage(Message message) throws RecordStoreException {
    RecordStore recordStore = null;
    try {
      // This static method invocation is normally hard to mock
      recordStore = RecordStore.openRecordStore(RECORD_STORE_NAME, true);
      byte[] bytes = encodeMessage(message);
      if (message.getId() == -1) {
        message.getId() = recordStore.addRecord(bytes, 0, bytes.length);
      } else {
        recordStore.setRecord(message.getId(), bytes, 0, bytes.length);
      }
    } finally {
      if (recordStore != null) {
        recordStore.closeRecordStore();
      }
    }
  }
}
</pre>
<h2>Desired Solution</h2>
<p>In this unit test of MessageDao we only test the happy-flow (when everything goes<br />
fine) to show the principle of static mocking. Please compare this to the MockME<br />
solution. </p>
<pre>public class MessageDaoTest extends TestCase {
  private MessageDao messageDao;        // Object under test
  private RecordStore recordStoreMock;  // Mock object 

  // Called by JUnit to initialize the test
  public void setUp() {
    // Create mock object for RecordStore as usual
    recordStoreMock = createMock(RecordStore.class);
    // tell mocking framework that static methods of class RecordStore
    // should be mocked
    staticMock(RecordStore.class); 

    // Create object under test
    messageDao = new MessageDao();
  } 

  // Called by JUnit to clean up after each test run
  public void tearDown() {
    messageDao = null;
  } 

  public void testAddMessage() throws Exception {
    // Set up expected behaviour
    // (This usually doesn’t work)
    expectStatic(RecordStore.openRecordStore(“MessageDao”, true))
      .andReturn(recordStoreMock);
    byte[] expectEncMess = “\u0004from\u0004text”.getBytes();
    expect(recordStoreMock.addRecord(aryEq(expectEncMess), eq(0), eq(10)))
      .andReturn(42);
    recordStoreMock.closeRecordStore(); 

    // Put the mocks in test state
    replayStatic(RecordStore.class);
    replay(recordStoreMock); 

    // Executing the code we want to test
    Message message = new Message(“from”, “text”);
    messageDao.addMessage(message);
    assertEquals(“Wrong message ID”, 42, message.getId()); 

    // Verify the behaviour
    verifyStatic(RecordStore.class);
    verify(recordStoreMock);
  }
}
</pre>
<p>This test sets up the expected method calls on RecordStore, then invokes the<br />
DAO and finally verifies its behavior. But unfortunately it is not possible to mock<br />
static methods as the binding is done at compile time. Or is it? </p>
<h2>Aspects to the rescue </h2>
<p>It	turns	out	that	this	is	possible.	Using	Aspect	Oriented	Programming	(AOP)	we<br />
can change the static methods to become mockable. Without going too much into<br />
details, AOP allows us to change the behavior of classes and methods after they have<br />
been compiled. Three things are needed: </p>
<ul>
<li>	A	pointcut	that	specifies	which	methods	the	aspect	should	change	(that	is	all<br />
static methods)
<li>	An	advice	that	that	allows	mocking	to	replace	the	original	behavior
<li>	An	implementation	of	the	mock,	replay,	verify	methods	that	allows	mocking<br />
classes
</ul>
<p>Let us start with the setup methods. To keep track of which classes we have<br />
mocked we create a Map that contains an EasyMock MockInvocationHandler for<br />
each class that we mock. MockInvocationHandler is a proxy object that performs<br />
the actual mocking and will receive method invocations instead of the real object.<br />
Notice the use of a Hashtable to make the map accesses thread safe. </p>
<pre>public class StaticMock {
    static Map<Class, MockInvocationHandler> mocks =
        new HashTable<Class, MockInvocationHandler>(); 

    public static void mock(Class type) {
        MockInvocationHandler h
        = new MockInvocationHandler((MocksControl) EasyMock.createControl());
        mocks.put(type, h);
    } 

    public static void replay(Class type) {
        mocks.get(type).getControl().replay();
    } 

    public static void verify(Class type) {
        mocks.remove(type).getControl().verify();
    } 

}
</pre>
<p>Then once we intercept a method call to a static method, find out if there is a<br />
MockInvocationHandler associated with that class and if so redirect the call to it.<br />
This method should not be static to avoid infinite recursion. The following advice<br />
does the trick: </p>
<pre>public	Object	mockMethodAdvice(ProceedingJoinPoint	jp) throws Throwable {
        // find the InvocationHandler associated with the class
        Class type = jp.getSignature().getDeclaringType();
        InvocationHandler h = mocks.get(type); 

        // if there is no InvocationHandler let the method call proceed
        // as normal
        if (h == null) {
            return jp.proceed();
        } 

        // otherwise redirect the method call to the proxy
        MethodSignature methodSignature
            = ((MethodSignature)jp.getSignature());
        return h.invoke(type, methodSignature.getMethod(), jp.getArgs());
    } </pre>
<p>Finally	we	need	to	tell	AspectJ	which	methods	it	should	apply	the	above	advice<br />
to. The following aspect uses a pointcut that catches ALL calls to ALL static meth-<br />
ods (call(static * *(..))). It might be a bit aggressive, but it works! If you want you can<br />
implement your own aspect with a more specialized pointcut, for example specific<br />
to your own application. </p>
<pre>
@Aspect
public class StaticMockAll extends StaticMock {
    @Pointcut(“call(static * *(..))”)
    public void anyStaticOperation() {}
    @Around(“anyStaticOperation()”)
    public Object aroundStaticMethods(ProceedingJoinPoint jp)
        throws Throwable
    {
        return mockMethodAdvice(jp);
    } 

}
</pre>
<p>Things to note: </p>
<ul>
<li>	Static	methods	can	be	mocked!
<li>	Native	methods	can	also	be	mocked	this	way!	By	using	the	“call”	pointcut	we<br />
change all code that tries to call the native methods and not the native method<br />
itself.	However,	note	that	class	loading	issues	are	not	avoided.	For	example,	Java<br />
ME implementations typically require that native libraries are loaded which<br />
can cause problems when unit testing.
<li>	AspectJ	is	required	to	make	this	work.	I	have	been	using	Eclipse	AJDT	plugin<br />
when writing and testing this code.
</ul>
<p>Please download and view the sample code for a simple working example of<br />
using this technique. Go to <a href="www.jayway.se/jayview">www.jayway.se/jayview</a> and download the zip file as-<br />
sociated with  this issue. </p>
<h2>Discussion </h2>
<p>There	are	other	are	ways	to	get	around	this	problem.	For	example	you	could	write<br />
small wrappers around these static methods and then consistently use the wrappers<br />
instead of the underlying implementation. This works, but each project will have<br />
its own wrappers which will probably make it harder to understand than using<br />
standard APIs.<br />
The approach taken by MockME is also an option, especially for handling stand-<br />
ard APIs such as the APIs for Java ME. However, this adds slightly more complexity<br />
to writing the tests, as you need to use the MockME specific methods.<br />
This new solution proposal is still very experimental, but using AOP or some<br />
other technique for bytecode manipulation seems to be a very promising solution<br />
to the problem of mocking static methods. However, to be successful a packaged<br />
solutions needs to: </p>
<ul>
<li>be a drop in jar file
<li>	work well with any IDE
<li> work with build systems such as ant or maven
</ul>
<h2>Conclusion </h2>
<p>So now static method are no longer bad design since we can mock them? No, not<br />
really. Static methods are still bad, but we no longer have to sacrifice or complicate<br />
testability when we are forced to use static methods. When writing new code you<br />
should use an object oriented design and use mock objects for your unit tests. The<br />
mocking techniques presented in this article are only a tool for testing things that<br />
weren’t testable before. This allows us to further increase the possible code coverage<br />
of our tests, but our design rules should not change. </p>
<h2>References</h2>
<p>Sample code available <a href="http://www.jayway.se/jayview/14/MockingStaticMethods.zip ">here</a></p>
<p>1. <a href="http://www.mockobjects.com/files/endotesting.pdf">Endo-Testing: Unit Testing with Mock Objects  </a><br />
2. JayView 13 - Java ME Testing Done Right<br />
3. <a href="http://www.easymock.org/">EasyMock</a><br />
4. <a href="http://junit.sourceforge.net/ ">JUnit</a><br />
5. <a href="http://www.eclipse.org/aspectj/">AspectJ</a><br />
6. <a href="http://www.eclipse.org/ajdt/">Eclipse AJDT</a><br />
7. <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">AOP</a> </p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/05/01/mocking-static-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JXPath simplifies Java queries</title>
		<link>http://blog.jayway.com/2006/08/04/jxpath-simplifies-java-queries/</link>
		<comments>http://blog.jayway.com/2006/08/04/jxpath-simplifies-java-queries/#comments</comments>
		<pubDate>Fri, 04 Aug 2006 10:30:52 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=259</guid>
		<description><![CDATA[Consider a company that contains many departments. Those departments contain employees, those employees have names, telephone numbers, and so on. To query a collection of companies and find, for example, all departments of companies in California with more than 10 employees, you could write something like this: &#160; for &#40;Iterator companies = database.getCompanies&#40;&#41;.iterator&#40;&#41;; companies.hasNext&#40;&#41;;&#41; &#123; [...]]]></description>
			<content:encoded><![CDATA[<p>Consider a company that contains many departments. Those departments contain employees, those employees have names, telephone numbers, and so on. To query a collection of companies and find, for example, all departments of companies in California with more than 10 employees, you could write something like this:</p>
<pre class="java">&nbsp;
<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Iterator</span></a> companies =
      database.<span style="color: #006600;">getCompanies</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">iterator</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      companies.<span style="color: #006600;">hasNext</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> 
&nbsp;
   Company company = <span style="color: #66cc66;">&#40;</span>Company<span style="color: #66cc66;">&#41;</span>companies.<span style="color: #006600;">next</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
   <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>company.<span style="color: #006600;">getLocation</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">equals</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;CA&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
      <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Iterator</span></a> departments =
            company.<span style="color: #006600;">getDepartments</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">iterator</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            departments.<span style="color: #006600;">hasNext</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> 
&nbsp;
         Department department = <span style="color: #66cc66;">&#40;</span>Department<span style="color: #66cc66;">&#41;</span>departments.<span style="color: #006600;">next</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
         <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>department.<span style="color: #006600;">getEmployees</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &gt; <span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</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>department<span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Using <a href="http://commons.apache.org/jxpath/">JXPath</a> you can simplify this:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// only needed once</span>
JXPathContext context = JXPathContext.<span style="color: #006600;">newContext</span><span style="color: #66cc66;">&#40;</span>database<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Iterator</span></a> departments = context.<span style="color: #006600;">iterate</span><span style="color: #66cc66;">&#40;</span>
      <span style="color: #ff0000;">&quot;/companies[location='CA']&quot;</span> +
      <span style="color: #ff0000;">&quot;/departments[count(employees) &gt; 10]&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>departments.<span style="color: #006600;">hasNext</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>
   <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>departments.<span style="color: #006600;">next</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>Two points should be noted from this example:</p>
<ul>
<li>The code using JXPath is considerably shorter. The query is concisely expressed in one statement.</li>
<li>You can take that expression out of the code and parameterize it, or put it in a configuration file.</li>
</ul>
<h3>Perfect for Unit Testing</h3>
<p>Unit testing often requires checking object hierarchies for particular values. You can use JXPath to express the components to be tested. For example, you can write a helper method in a JUnit test:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * tests using a JXPath to express the required
 * component to test against. Note that nulls
 * aren't catered for!
 * @param path the path to find the object to
 *        test against
 * @param testable the base object to test
 * @param required the required result
 */</span>
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">void</span> assertFromPath<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> path,
                            <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> testable,
                            <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> required<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
   JXPathContext context = JXPathContext.<span style="color: #006600;">newContext</span><span style="color: #66cc66;">&#40;</span>testable<span style="color: #66cc66;">&#41;</span>;
   assertTrue<span style="color: #66cc66;">&#40;</span>required.<span style="color: #006600;">equals</span><span style="color: #66cc66;">&#40;</span>context.<span style="color: #006600;">getValue</span><span style="color: #66cc66;">&#40;</span>path<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and then you can use this in tests:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testBankAccount<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
   <span style="color: #808080; font-style: italic;">// you get a bank account object from some operation...</span>
   Account account = .... 
&nbsp;
   <span style="color: #808080; font-style: italic;">// then test against it</span>
   assertFromPath<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/accountHolder/name&quot;</span>, account, <span style="color: #ff0000;">&quot;John Smith&quot;</span><span style="color: #66cc66;">&#41;</span>;
   assertFromPath<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/accountHolder/opened&quot;</span>, account, DATE_OPENED<span style="color: #66cc66;">&#41;</span>;
   assertFromPath<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/accountHolder&quot;</span> + <span style="color: #ff0000;">&quot;/transactions[1]/amount&quot;</span>,
         account, INITIAL_PAYMENT<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Read more in <a href="http://today.java.net/pub/a/today/2006/08/03/java-object-querying-using-jxpath.html">this java.net article</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2006/08/04/jxpath-simplifies-java-queries/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>DDSteps &#8211; data driven sanity</title>
		<link>http://blog.jayway.com/2005/08/01/ddsteps-data-driven-sanity/</link>
		<comments>http://blog.jayway.com/2005/08/01/ddsteps-data-driven-sanity/#comments</comments>
		<pubDate>Sun, 31 Jul 2005 22:00:00 +0000</pubDate>
		<dc:creator>Björn Granvik</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[open source]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7391</guid>
		<description><![CDATA[”Aaarrrgh”, is not only the sound of pirates. It is also the desperate cry from programmers who realize what a mess they’ve got themselves into. This is especially true in testing. The number of combination that you should run your code through easily outpaces you. But fear no more, here’s one pill with a great [...]]]></description>
			<content:encoded><![CDATA[<p><strong>”Aaarrrgh”, is not only the sound of pirates. It is also the desperate cry from programmers who realize what a mess they’ve got themselves into. This is especially true in testing. The number of combination that you should run your code through easily outpaces you. But fear no more, here’s one pill with a great taste ordered by Dr Jay DDSteps.</strong><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2005/08/ddstepslogo.png"><br />
<img src="http://blog.jayway.com/wordpress/wp-content/uploads/2005/08/ddstepslogo.png" alt="" title="DDSteps" width="77" height="100" class="alignnone size-full wp-image-7401" /></a></p>
<p>DDSteps is on open source project the brainchild of Adam Skogman which aim to make sense of your unit tests when they consist of god knows how many permutations of input. Read on to find out exactly how.</p>
<h2>A Typical Project</h2>
<p>Let us tell the tale of a too-successful project. It all started out as a prototype web site, quickly hacked together over a week to show to the investors. Big hit! Some swift fixes later it went live slow, rocky, but making money. Refactoring the code was an inevitable next. As new people joined the project, test driven development was introduced to make sure that programmers did not break each other’s code. The unit tests covered more and more of the code. Even the happy hackers in the group had to admit that things were getting better and bugs were fewer.<br />
The business side of the now booming company poured new feature requests into the development and demanded that they appear in production “real soon”. Therefore, a shorter release cycle was introduced, releasing every month. Also, a quality assurance test team was set up to test each release. So developers had to “pre-test” the release before the test team got it. Testing now took two weeks. Bugs were all around and had to be corrected. At this point the site went global, requiring small specific changes for each country.<br />
This is when it all broke down. Testing now took over a month and bugs were often reported months after the release was made. Nobody wanted to re-release and do all those tests again, so the site went into production with known, serious bugs. It was at this point that the programmers went: “Aaarrrgh!”</p>
<h2>The Remedy</h2>
<p>Testing your solution for every type of input and making sure it will pass function tests is difficult at best. Usually, this is done “by hand” and requires real people. And, yes, it is boring and time consuming. So you have to automate it, just like you did with JUnit tests for unit testing.<br />
By Function tests we mean, ”Does it work like the use case says it should”. We mean full, system, end-to-end tests, using a production-like environment. We mean using a browser, surfing the web application and then checking the real database for results.<br />
Automating function tests is hard, mostly since they suffer from the same problem as the manual testing. Many of the tests are the same; just the data is slightly different in each test. </p>
<p>Data driven testing on the other hand separates the testing code from its input. This and the reusable test steps makes it easy to maintain and evolve the test cases, you get reuse instead of copy-paste. Need another field? Just add new column in your input and handle it in your test case and voila. There will be no explosion of test methods, no massive round of changes!<br />
Ok, let’s start from the top and look what DDSteps is and how it makes your life easier.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ddsteps4.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ddsteps4-300x161.png" alt="" title="DDSteps process" width="300" height="161" class="alignnone size-medium wp-image-7396" /></a><br />
<em>Figure: Overview of the DDSteps’ process. 1) Input is retrieved from an Excel file and populates your test cases and test step POJOs. 2) Yellow is your code. TestSomething is your test method that (re)uses different test steps. 3) The fixture F typically sets the database in the correct state for the test. The Navigators, Executors and Validators in this example use JWebUnit to perform their respective step. 4) Output – reports, console etc.</em></p>
<p>Since most tests are the same, with just different data, first we separate data (input) and the test code. The data, found in an Excel file, is inserted into your test case, each row becoming a test case run. The second important part is the framework of reusable test steps. Test cases are broken down into steps:</p>
<ul>
<li>Fixture – set up the needed data in your database. </li>
<li>Navigator – Navigate your web site. </li>
<li>Executor – Input data into the system, like filling out a form on a page and pressing a button. </li>
<li>Validator – Validate the output on a page or a row in the database etc. </li>
<li>Cleaner – Clean up any mess you have made.</li>
</ul>
<p>You implement these types of test steps using for instance JWebUnit and Spring JDBC. You can easily imagine that many test cases will use the same executor, since they pass through the same web page, so reuse is everywhere.<br />
Finally, DDSteps is just standard JUnit, so the test outcome is reported back via Ant, CruiseControl or your preferred JUnit compatible IDE. It integrates perfectly into your existing environment.</p>
<h2>Divide and Conquer</h2>
<p>Let us dive deeper. Again, how do we separate data from the code? You can do this several ways. We chose to use Excel. It’s not only easy to format and to enter data, it’s a de facto standard and you can use formulas etc. And if you want you can always use OpenOffice.<br />
Let us take the following use case from PetClinic from Spring – ‘Add new pet’.<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ddsteps1.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ddsteps1.png" alt="" title="DDSteps &#039;Add new Pet&#039;" width="303" height="392" class="alignnone size-full wp-image-7392" /></a><br />
<em>Figure: Use case ‘Add New Pet’. Green is data that is put into an Excel file. See next figure. The letters N, E and V are our test steps for this use case.</em></p>
<p>We have now divided our use case above into reusable test steps. Next is the Excel file. From our test case we can see that we need: Owner, pet name etc.<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ddsteps2.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ddsteps2.png" alt="" title="DDSteps input data" width="590" height="351" class="alignnone size-full wp-image-7393" /></a><br />
<em>Figure: The Excel file that holds our input and fixture data.</em></p>
<p>Each test method is entered on separate worksheets. The fixture data we need for the database is entered as well. DDSteps find your test data in the spreadsheet using the method names in your test code, and uses JavaBeans get/set to inject data into your test case and your test steps.</p>
<h2>Code</h2>
<p>Next is the test code. Let us look at just one part of it – navigating. The example covers points 1-6,7 of the use case, i.e. the first and second test step. In order for this part to work our HTML pages need to be written with JWebUnit in mind, i.e. an id is put on elements, so that we can find it and “click” etc. Let us assume this has been done. We also use Spring even though this is optional.<br />
The test case would then look something like this.</p>
<h3>PetclinicTestCase.java</h3>
<pre>
// Our test case, see PetFTest.xls for input.
public class PetFTest extends PetclinicTestCase {

    protected NavigateToAddPet nav;
    protected ValidatePetForm valForm;
    ...

    // The test method, same as tab name in Excel file.
    public void testAddPet_Ok() throws Exception {
        nav.runStep();
        valForm.runStep();
        ...
    }

    // Used from data file to access navigator properties, e.g. “nav.name”.
    public NavigateToAddPet getNav() {
        return nav;
    }
    ...
</pre>
<p>In the code snippet above we declare our PetFTest test case that inherits from PetclinicTestCase. This base class only holds common things like web browser, fixture etc. The test method testAddPet_Ok is simple and reduced to only use necessary test steps, nav (NavigateToAddPet) and valForm (ValidatePetForm).<br />
Also note that we have getNav() which is used as the first part in the data file “nav. name”. The access to properties is JavaBean based, i.e. using get/set methods. We will only look at the first test step, the navigator NavigateToAddPet, since the other steps are similar in concept.</p>
<h3></h3>
<pre>
public class NavigateToAddPet extends JWebUnitTestStep {

    // Reuse another navigation step
    NavigateToOwner navigateToOwner;

    public NavigateToAddPet(WebBrowser webBrowser) {
        // The web browser is injected by Spring.
        super(webBrowser);
        navigateToOwner = new NavigateToOwner(webBrowser);
    }

    public void runStep() throws Exception {

        // Delegate
        navigateToOwner.runStep();

        // Click ‘Add new pet’ button,
        // which is the submit button in the form ’formAddPet’
        setWorkingForm(”formAddPet”);
        submit();

        // Snapshot of web page.
        writeTrail(”Add New Pet Form”);
    }

    // Full name is populated from ”nav.name” in the data file.
    public void setName(String name) {
        navigateToOwner.setName(name);
    }
}
</pre>
<p>This test step is a composite of another navigator, NavigateToOwner, and going to the “Add new Pet” page. WriteTrail will write specified html page to the hard disk, a visual page debugger if you will.</p>
<h2>Run</h2>
<p>Having come this far, we can now run our test code and get the result.<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ddsteps3.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ddsteps3-300x198.png" alt="" title="DDSteps output in Eclipse" width="300" height="198" class="alignnone size-medium wp-image-7394" /></a><br />
<em>Figure: And finally the output, in this example, in Eclipse.</em></p>
<p>Oops, better fix our code! In the example above we see the errors per row, not just by test method.</p>
<h2>What happened to the Project?</h2>
<p>When our team employ DDSteps, they can automate their tests, and cut down the time for testing to minutes, not weeks. This means you can run all function tests every night or every time the source code changes! Suddenly, you can release to production with no bugs because as soon as you know there is a one, you fix it during ordinary development. Function testing is now a part of development, not an afterthought.</p>
<h2>Conclusion</h2>
<p>DDSteps both tries to break new ground and to reuse solutions perfected by others. We think it is a good mix to implement function tests using data driven testing. Is it for you? Who knows? Get it from www.ddsteps.org to see for yourself.<br />
<em>Originally published in <a href="http://jayway.com/jayculture/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2005/08/01/ddsteps-data-driven-sanity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

