<?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>Tales From The Cloud &#187; testing</title>
	<atom:link href="http://blog.newsplore.com/tag/testing/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.newsplore.com</link>
	<description>Everything beta</description>
	<lastBuildDate>Sun, 05 Feb 2012 09:03:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Unit testing with Commons HttpClient library</title>
		<link>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient</link>
		<comments>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient#comments</comments>
		<pubDate>Wed, 10 Feb 2010 00:31:25 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1442</guid>
		<description><![CDATA[I want to write testable code and occasionally I bump into frameworks that make it challenging to unit test. Ideally I want to inject a service stub into my code then control the stub&#8217;s behavior based on my testing needs. Commons Http Client from Jakarta facilitates integration with HTTP services but how to easily unit [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F09%2Funit-testing-with-httpclient"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F09%2Funit-testing-with-httpclient" height="61" width="51" /></a></div><p>I want to write testable code and occasionally I bump into frameworks that make it challenging to unit test. Ideally I want to inject a service stub into my code then control the stub&#8217;s behavior based on my testing needs.<br />
<a href='http://hc.apache.org/httpclient-3.x/'>Commons Http Client</a> from Jakarta facilitates integration with HTTP services but how to easily <i>unit test</i> code that depends on the HttpClient library? Turns out it&#8217;s not that hard.<br />
I&#8217;ll cover both 1.3 and the newer 1.4 versions of the library since the older v1.3 is still widely used.<br />
Here&#8217;s some typical service (HttpClient v1.3) we want to test. It returns the remote HTML page title:</p>
<pre>
public class RemoteHttpService {
   private HttpClient client;

   public String getPageTitle(String uri)  throws IOException {
     String contentHtml = fetchContent(uri);
     Pattern p = Pattern.compile("&lt;title&gt;(.*)&lt;/title&gt;");
     Matcher m = p.matcher(contentHtml);
     if(m.find()) {
        return m.group(1);
     }
     return null;
   }

   private String fetchContent(String uri)  throws IOException {
      HttpMethod method = new GetMethod("http://blog.newsplore.com/" + uri);
      int responseStatus = client.executeMethod(method);
      if(responseStatus != 200) {
        throw new IllegalStateException("Expected HTTP response status 200 " +
"but instead got [" + responseStatus + "]");
      }
      byte[] responseBody = method.getResponseBody();
      return new String(responseBody, "UTF-8");
   }

   public void setHttpClient(HttpClient client) {
      this.client = client;
   }
}
</pre>
<p>with the HttpClient is injected at runtime (via some IoC container or explicitly).<br />
To be able to unit-test this code we have to come-up with a stubbed version of the HttpClient and emulate the GET method. </p>
<p><span id="more-1442"></span><br />
 What we really want is to be able to control the byte array returned by method.getResponseBody() and although we can inject a mocked HttpClient, the actual class that is responsible for producing the response body is GetMethod which is instantiated (and completely encapsulated) in the method body so we can&#8217;t inject a stubbed GetMethod version directly.<br />
The solution is to create a simple HttpClient mock that is able to control the response status and response body. Here it is:</p>
<pre>
package org.apache.commons.httpclient;

import org.apache.commons.httpclient.*;

public class HttpClientMock extends HttpClient {
   private int expectedResponseStatus;
   private String expectedResponseBody;
   public HttpClientMock (int responseStatus, String responseBody) {
      this.expectedResponseStatus = responseStatus;
      this.expectedResponseBody = responseBody;
   }
   @Override
   public int executeMethod(HttpMethod method) {
      ((HttpMethodBase)method).setResponseStream(
new ByteArrayInputStream(expectedResponseBody.getBytes("UTF-8")));
      return expectedResponseStatus;
   }
}
</pre>
<p>There are two things to notice: Firstly, I placed HttpClientMock in the org.apache.commons.httpclient package to be able to have access to the protected member HttpMethodBase:setResponseStream. Secondly, I downcasted HttpMethod to HttpMethodBase to get access to setResponseStream (it&#8217;s safe since all concrete HttpMethods (GetMethod, PostMethod, etc) inherit from it).</p>
<p>Now I can unit test RemoteHttpService like this:</p>
<pre>
public class RemoteHttpServiceTest {
   private RemoteHttpService remoteHttpService = new RemoteHttpService();

   @Test
   public void extractTitleResponseOK()  throws IOException {
      String pageTitle = "A Title";
      String responseBody = "&lt;title&gt;" + pageTitle + "&lt;/title&gt;";
      HttpClientMock mockHttpClient = new HttpClientMock(200, responseBody);
      remoteHttpService.setHttpClient(mockHttpClient);
      String resultedPageTitle = remoteHttpService.getPageTitle(""); //home page
      Assert.assertTrue(pageTitle.equals(resultedPageTitle));
   }
}
</pre>
<p>I can also add a negative test:</p>
<pre>
   @Test(expected = IllegalStateException.class)
   public void respondsWithInternalServerError()  throws IOException {
      HttpClientMock mockHttpClient = new HttpClientMock(500, "");
      remoteHttpService.setHttpClient(mockHttpClient);
      remoteHttpService.getPageTitle("");
   }
</pre>
<p>For HttpClient version 4.x here&#8217;s the refactored service code :</p>
<pre>
   private String fetchContent(String uri) {
        HttpGet httpget = new HttpGet("http://blog.newsplore.com/" + uri);
        HttpResponse response = client.execute(httpget);
        int responseStatus = response.getStatusLine().getStatusCode();
        if(responseStatus != 200) {
           throw new IllegalStateException("Expected HTTP response status 200 " +
"but instead got [" + responseStatus + "]");
        }
        InputStream responseStream = response.getEntity().getContent();
        byte[] responseBytes = IOUtils.toByteArray(responseStream);
        return new String(responseBytes, "UTF-8");
   }
</pre>
<p>Turns out that implementing a HttpClient mock by extending the DefaultHttpClient (the provided implementation of HttpClient) is not easy. The method I want to override is <i>public HttpResponse execute(HttpUriRequest request) </i> which is marked &#8216;final&#8217; and the code in DefaultHttpClient looks just too complex to inject stubbed behavior.<br />
What we actually want is to be able to control the return of the aforementioned &#8216;execute&#8217; method since it encapsulates the response status and body (better encapsulation than HttpClient 1.3 if you noticed).<br />
Luckily in this case we can use a readily available mocking framework, Mockito that can stub this entire method and return an HttpResponse that we instantiate with the needed status and response body. Here&#8217;s how to rewrite the tests using it:</p>
<pre>
@Test
public void extractTitleResponseOK() throws IOException {
	String pageTitle = "A Title";
	String responseBody = "";
	HttpResponse response = prepareResponse(200, responseBody);
	HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
	Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
			.thenReturn(response);

	remoteHttpService.setHttpClient(mockHttpClient);
	String resultedPageTitle = remoteHttpService.getPageTitle(""); // home page
	Assert.assertTrue(pageTitle.equals(resultedPageTitle));
}

@Test(expected = IllegalStateException.class)
public void respondsWithInternalServerError() throws IOException {
	HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
	HttpResponse response = prepareResponse(500, "");
	Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
			.thenReturn(response);
	remoteHttpService.setHttpClient(mockHttpClient);
	remoteHttpService.getPageTitle("");
}

private HttpResponse prepareResponse(int expectedResponseStatus,
               String expectedResponseBody) {
      HttpResponse response = new BasicHttpResponse(new BasicStatusLine(
    		  new ProtocolVersion("HTTP", 1, 1), expectedResponseStatus, ""));
      response.setStatusCode(expectedResponseStatus);
      try {
		response.setEntity(new StringEntity(expectedResponseBody));
	} catch (UnsupportedEncodingException e) {
		throw new IllegalArgumentException(e);
	}
	return response;
}
</pre>
<p>The meat of the above code is</p>
<pre>
HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
HttpResponse response = prepareResponse(...);
Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
	.thenReturn(response);
</pre>
<p>that instructs the mocked HttpClient to return a HttpResponse that is instantiated in the test context (seeded if you like) when &#8216;execute&#8217; is called (check Mockito documentation for more details on the syntax).</p>
<p>That&#8217;s it. Happy testing.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Continuous everything?</title>
		<link>http://blog.newsplore.com/2009/10/15/continuous-everything</link>
		<comments>http://blog.newsplore.com/2009/10/15/continuous-everything#comments</comments>
		<pubDate>Thu, 15 Oct 2009 06:16:09 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1376</guid>
		<description><![CDATA[I admit that I regard automation as a dull but vital part in the success of a project. Automation had evolved into Continuous Integration, a powerful toolset allowing frequent and regular building and testing of the code. I won&#8217;t get into what CI is (check the internets). Instead, I am going to explore a couple [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F10%2F15%2Fcontinuous-everything"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F10%2F15%2Fcontinuous-everything" height="61" width="51" /></a></div><p>I admit that I regard automation as a dull but vital part in the success of a project. Automation had evolved into <a href="http://en.wikipedia.org/wiki/Continuous_integration">Continuous Integration</a>, a powerful toolset allowing frequent and regular building and testing of the code. I won&#8217;t get into what CI is (<a href="http://martinfowler.com/articles/continuousIntegration.html">check</a> the internets). Instead, I am going to explore a couple of aspects of CI that can be added to the artifacts of the development process and note some others that cannot.</p>
<p><b>Continuous performance</b><br />
You wrote performance tests. You can run performance tests by firing a battery of tests from a client machine and targeted on an arbitrary environment where the application lives. The test results are collected on the client and you can publish them on a web server. Why not automating this completely then? To accomplish this, automate the execution, gathering and publishing of the performance results. Daily performance indicators not only increase visibility of the progress of the application but it becomes much easier to fix a performance degradation on a daily changeset than between two releases. There are a couple of factors that may add complexity to establishing performance tests:<br />
<i>Dealing with dependencies</i><br />
The obvious rule of thumb is to minimize dependencies. However, if there still are dependencies on other (perhaps external) systems, use mocks and to isolate the system you&#8217;re testing for performance. We&#8217;re talking about nightly performance tests so don&#8217;t put unnecessary stress where you shouldn&#8217;t.<br />
Finally, the main artifact of the final integration (done once per iteration) is a running environment where all components run together, in a production-like setup. Use this environment to run your system performance test where you measure the current performance against the baseline.<br />
<i>Measuring relative performance</i><br />
The environment you&#8217;re using for the nightly PT cycle most likely will not be a perfect mirror of production (especially true when dealing with geographically distributed systems). Use common-sense to establish the ratio between the two environments then derive rough production performance numbers using it (assuming a linear CPU/Throughput relationship).</p>
<p><b>Continuous deployment</b><br />
This is as simple as it sounds: automate the install. Make it dead easy to deploy the application in any environment by providing installation scripts. Simplify the configuration down to a single file that is self-documented and easily understood by non-programmers (read Operations Teams). The goal here is to unlock a powerful tool: making the application installable and upgradable with a click of a button. If all the other pieces of the continuum are in place then you could confidently deploy your application in production it on a much tighter release cycle, even on a daily basis. Deployment and integration become tasks in the background rather than first-class events.</p>
<p><b>More continuous</b><br />
Since I am just fresh off the Agile Testing Days conference and I have learned a few more Cs from the distinguished speakers which I term as Soft Cs since they involve constant human engagement:<br />
- Continuous learning (Declan Whelan)<br />
- Continuous process improvement (Stuart Reid)<br />
- Continuous acceptance testing (i.e. stakeholder signoff at the end of every sprint) &#8211; Anko Tijman<br />
- Continuous customer involvement (Anko Tijman)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2009/10/15/continuous-everything/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

