<?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>Shaun Abram &#187; Testing</title>
	<atom:link href="http://www.shaunabram.com/category/testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.shaunabram.com</link>
	<description>Java and Technology weblog</description>
	<lastBuildDate>Wed, 18 Jan 2012 00:39:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Add log4j logging for a unit test in IntelliJ</title>
		<link>http://www.shaunabram.com/log4j-for-a-unit-test-in-intellij/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=log4j-for-a-unit-test-in-intellij</link>
		<comments>http://www.shaunabram.com/log4j-for-a-unit-test-in-intellij/#comments</comments>
		<pubDate>Sat, 03 Sep 2011 18:36:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[intellij]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[log4j]]></category>
		<category><![CDATA[mybatis]]></category>
		<category><![CDATA[unittesting]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1294</guid>
		<description><![CDATA[In IntelliJ Click: Run -> Edit Configuration Select your test configuration (or add a new one) In VM parameters, add -Dlog4j.configuration=file:/C:/dev/config/log4j.xml (Or wherever your log4j properties file is) That&#8217;s it. The test should now run with log4j logging (although obviously you need to have the necessary log4j jars available). This example uses a windows file [...]]]></description>
			<content:encoded><![CDATA[<p>In IntelliJ</p>
<ul>
<li>Click: Run -> Edit Configuration</li>
<li>Select your test configuration (or add a new one)</li>
<li>In VM parameters, add<br />
-Dlog4j.configuration=file:/C:/dev/config/log4j.xml<br />
(Or wherever your log4j properties file is)</li>
</ul>
<p>That&#8217;s it. The test should now run with log4j logging (although obviously you need to have the necessary log4j jars available).<br />
This example uses a windows file format, but will work equally well with *nix.</p>
<p>I use this approach for turning on <a href="http://www.mybatis.org/">MyBatis</a> logging for individual tests. See <a href="http://code.google.com/p/mybatis/wiki/Logging">here </a>for a basic setup of a log4j.xml file to enable logging with MyBatis. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/log4j-for-a-unit-test-in-intellij/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>EasyMock</title>
		<link>http://www.shaunabram.com/easymock-2/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=easymock-2</link>
		<comments>http://www.shaunabram.com/easymock-2/#comments</comments>
		<pubDate>Wed, 17 Aug 2011 02:20:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[unittesting]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1195</guid>
		<description><![CDATA[EasyMock is an open source library for creating, and defining the behavior of, mock objects as part of your unit tests. This article describes how to use EasyMock (v3.0), including its record/playback approach, after setting the context with an brief introduction to unit testing in general and the associated need for mock objects. Unit Testing [...]]]></description>
			<content:encoded><![CDATA[<p>EasyMock is an open source library for creating, and defining the behavior of, mock objects as part of your unit tests. This article describes how to use EasyMock (v3.0), including its record/playback approach, after setting the context with an brief introduction to unit testing in general and the associated need for mock objects.<br />
<span id="more-1195"></span> </p>
<h3>Unit Testing</h3>
<p>The benefits of unit testing code are many and include allowing us to find problems early, enable refactoring with confidence, and even provide a form of documentation for our code. Writing code with testing in mind (or, in the <a href="http://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530/ref=sr_1_1?ie=UTF8&#038;qid=1313544869&#038;sr=8-1">TDD</a> world, to make already written tests pass) helps us to write code that is modular, with low coupling and high cohesion.</p>
<p>Unit testing is a way to verify that a unit of code works as we expect and want. In Java, that unit is often centered around a method. Sometimes a small part of one method (such as a particularly if block); sometimes several methods (for example, in the case of the public method under test calling one or more private methods). However, what a unit test should not do is test outside its own class boundary since this gets in to the realm of integration testing.  </p>
<h3>Using Mock Objects</h3>
<p>Inevitably however, your class will rely on the behavior of other classes. So, the issue then becomes how to deal with those other classes. We somehow need to isolate, or control, their behavior in order to be able to focus on the unit under test. (We will either test that other code separately or, in the case of 3rd party libraries, assume that it works well already.) </p>
<p>The solution to isolating your unit under test from the other collaborating classes is to use mock objects in place of those collaborators. Mock objects allow us to focus on just the code under test by mocking the collaborator&#8217;s behavior. We specify expectations for how our code will interact (methods calls and return values), control those interactions and confirm that everything in our unit test code works as expected. Mock objects are, in essence, a way to test our code in isolation from the rest of our software world.</p>
<p>Fortunately, in the Java world, we have several mock object frameworks available, including <a href="http://www.jmock.org/">JMock</a>, <a href="http://mockito.org/">Mockito</a> and <a href="http://easymock.org/">EasyMock</a>. There are some interesting discussions on the relative merits of each <a href="http://stackoverflow.com/questions/22697/whats-the-best-mock-framework-for-java">here</a> and <a href="http://softwareinabottle.wordpress.com/2010/09/12/finding-the-mock-framework-that-best-suits-me-part-1-the-contenders/">here</a>. This article focuses on the functionality of EasyMock.</p>
<h1>EasyMock</h1>
<p>EasyMock uses a record/playback paradigm for unit testing with mock objects. In record mode, you record what methods you expect to be called on your mock objects (and specify how you want your mock to respond). In playback mode, your mocks wait for those expected calls, playing back the canned responses you have specified. EasyMock will alert you to any unexpected behavior, such as missing calls and incorrect argument or return values and can also alert you to other behavior such as unexpected method calls.</p>
<p>These are the basic steps for using an EasyMock mock object:</p>
<ol>
<a href="#1">
<li>Create a Mock Object</li>
<p></a><br />
<a href="#2">
<li>Record the expected behavior</li>
<p></a><br />
<a href="#3">
<li>Switch to replay state</li>
<p></a><br />
<a href="#4">
<li>Call the methods under test</li>
<p></a><br />
<a href="#5">
<li>Verify the mock was used as expected</li>
<p></a>
</ol>
<p><a name="1"><br />
<h2>1. Creating Mocks</h2>
<p></a><br />
Creating a mock is simple. Simply call createMock and pass in the class of the interface to be mocked, For example:</p>
<pre><code>    MyInterface mock = org.easymock.EasyMock.createMock(MyInterface.class);</code></pre>
<p>Or better yet, statically import the EasyMock static methods in you class import statements. For example:</p>
<pre><code>    import static org.easymock.EasyMock.*;
    …
    MyInterface mock = createMock(MyInterface.class);</code></pre>
<p>(Note that this static import approach applies to pretty much all of the EasyMock methods discussed in this article).</p>
<p>That&#8217;s it! Mock created. I have included some details on more customized mocks below, but in most cases, you can simply skip to the next step: <a href="#2">specifying the expected behavior</a>.</p>
<h3>Mock creation specifics</h3>
<p>Using <code>createMock</code> creates a mock object that has 2 notable characteristics:</p>
<ol>
<li>
Order checking is disabled by default. That is, you can specify the method call expectations (more later) in any order you wish &#8211; they do not need to match the actual order of the method invocations at test run time.</li>
<li>Calls to unexpected methods cause the test to fail</li>
</ol>
<p>However, EasyMock provides two other approaches for creating mocks&#8230;</p>
<h3>Strict/Nice mocks</h3>
<h4>Strict Mocks</h4>
<p>A strict Mock Object has order checking enabled by default (and calls to unexpected methods still cause the test to fail).</p>
<pre><code>    MyInterface mock = org.easymock.EasyMock.createStrictMock(MyInterface.class);</code></pre>
<p>Since method order invocation is important under normal use, I often create my mocks as &#8216;strict&#8217; by default.</p>
<h4>Nice Mocks</h4>
<p>Like a regular mock, order checking is disabled by default but &#8216;nice&#8217; mocks will also allow calls to unexpected methods to pass unnoticed. Nice mocks also have another useful behavior: They will do their best to create a return value for unexpected method invocations. Specifically, they will return 0 (for methods with a numeric return type), false (for methods with a boolean return type) or null (for all other methods). </p>
<p>I find nice mocks particular use for testing legacy classes (or classes that were perhaps not created with unit testing in mind) that may interact with a large number of other classes which my current tests have no concern with.</p>
<h3>Partial Mocks</h3>
<p>EasyMock also provides the capability to mock specific methods of a class while not mocking (i.e. keeping the real behavior) of others. I have not personally used this functionality yet, but it is available via the <code>createMockBuilder</code> method, which returns a <a href="http://easymock.org/api/easymock/3.0/org/easymock/IMockBuilder.html">IMockBuilder</a>interface.</p>
<h3>Mocking concrete classes</h3>
<p>The final point on mock creation is that although EasyMock (and indeed the use of mock objects in general) is most often associated with mocks of interfaces, you can in fact also create mocks of concrete class also. You simply use </p>
<pre><code>    org.easymock.classextension.EasyMock.createMock(...)</code></pre>
<p>instead of the more conventional</p>
<pre><code>    org.easymock.EasyMock.createMock(...);</code></pre>
<p>e.g.</p>
<pre><code>    ConcreteClass mock = org.easymock.classextension.EasyMock.createMock(ConcreteClass.class);</code></pre>
<p><a name="2"><br />
<h2>2. Record the expected behavior for your mock</h2>
<p></a><br />
After creating our mock object, we next need to tell EasyMock how we expect that mock to be used, that is, what methods we expect to be called on it.</p>
<h3>2.1 Simplest case</h3>
<p>In the simplest case where the expected method call has no return values (i.e. void) and accepts no arguments, you simply just call the method directly. For example:</p>
<pre><code>    mock.expectedOperation() </code></pre>
<p>EasyMock still picks up &#038; records the expectation.</p>
<p>Note that if you need to apply other expectations (such as expected Exceptions, or number of invocations as discussed later) to these simple cases, you can do so by invoking <code>expectLastCall()</code> followed by your expectations.</p>
<p>In addition to these simple calls however, EasyMock also provides the capabilities to specify return types and argument values, where required&#8230;</p>
<h3>2.2 Specifying return values</h3>
<p>If the call to expectedOperation returns a value, you must specify what EasyMock will return to your calling code. This can be done using the <code>andReturn()</code> method (a method provided by the return object of <code>EasyMock.expect()</code>, <a href="http://easymock.org/api/easymock/3.0/org/easymock/IExpectationSetters.html">IExpectationSetters</a>). </p>
<p>For example:</p>
<pre><code>    EasyMock.expect(mock.expectedOperation()).andReturn(expectedReturnValue);</code></pre>
<p>Where “expectedReturnValue” can be any object or primitive that matches expectedOperation’s return type.</p>
<h4>Gotcha:</h4>
<p>If the expected operation does indeed return a value, and you do not specify<br />
e.g. EasyMock.expect(mock.expectedOperation());<br />
You will get an error like:</p>
<pre><code>    java.lang.IllegalStateException: missing behavior definition for the preceding method call expectedOperation()</code></pre>
<p>Note that you can also get this error if you forget to call replay() before using a mock – more below.</p>
<h4>Advanced return values</h4>
<p>If you need more advanced return type creation, e.g. creating a value (or an Exception) at runtime, you can use <code>andAnswer(IAnswer answer)</code>. See <a href="http://easymock.org/api/easymock/2.4/org/easymock/IAnswer.html">IAnswer</a> for more details.</p>
<h3>2.3 Specifying arg values</h3>
<p>In the simplest approach, to specify an argument value, you just pass it with the expected method call, as in:</p>
<pre><code>    mock.expectedOperation(argValue)</code></pre>
<p>or</p>
<pre><code>    EasyMock.expect(mock.expectedOperation(argValue)).andReturn(expectedReturnValue);</code></pre>
<p>EasyMock simply compares the actual method arguments and the expected arguments by using <code>equals()</code>. </p>
<h4>Flexible Argument Matchers</h4>
<p>It is also possible to have EasyMock adopt a more flexible approach to matching actual and expected arguments. For example, you may be happy to just have </p>
<ul>
<li>any Object passed</li>
<li>A String starting with a certain value</li>
<li>A number in a certain range</li>
</ul>
<p>Easyock support these, and more, using argument matchers such as</p>
<ul>
<li>anyObject()</li>
<li>startsWith(String prefix)</li>
<li>eq(X value, X delta)</li>
</ul>
<p>For example:</p>
<pre><code>    expect(mock.expectedOpreation(EasyMock.anyInt()));</code></pre>
<p>See the <a href="http://easymock.org/api/easymock/3.0/org/easymock/EasyMock.html">EasyMock class API</a> for more details (or the EasyMock <a href="http://easymock.org/Documentation.html">readme</a>).</p>
<h3>2.4 Specifying how many calls are expected</h3>
<p>EasyMock also provides the capability to either relax or tighten the rules regarding the number of calls expected for a method.</p>
<h4>Specifying an exact number of calls</h4>
<p>To specify that a method must be called a certain number of times, we can just repeat the expected call the required number of time, e.g.</p>
<pre><code>    EasyMock.expect(mock.expectedOperation()).andReturn(expectedReturnValue);
    EasyMock.expect(mock.expectedOperation()).andReturn(expectedReturnValue);</code></pre>
<p>But this can get tedious for large numbers of calls, so we can also do:</p>
<pre><code>EasyMock.expect(mock.expectedOperation()).<strong>times(2)</strong>.andReturn(expectedReturnValue);</code></pre>
<h4>Specifying an inexact number of calls</h4>
<p>There are a number of other methods (again, all provided by the return object of EasyMock.expect()) allowing us to specify looser rules on the number of expected method calls. These are:</p>
<ul>
<li>anyTimes() </li>
<li>atLeastOnce() </li>
</ul>
<p><a name="3"><br />
<h2>3. Switch to replay state</h2>
<p></a><br />
Switching a mock object to replay state is simply done by calling EasyMock.replay(), passing in the mock object.<br />
e.g. </p>
<pre><code>    EasyMock.replay(mock).</code></pre>
<p>This should be done for all mocks you have created (or, alternatively, call <code>EasyMock.replayAll()</code>)<br />
If you forget to call replay() before using a mock you will get this error:</p>
<pre><code>    java.lang.IllegalStateException: missing behavior definition for the preceding method call expectedOperation()</code></pre>
<p>Calling replay tells EasyMock that you are no longer specifying expected method calls and moving into replay mode.</p>
<p><a name="4"><br />
<h2>4. Call the methods under test</h2>
<p></a><br />
This part is not really EasyMock specific since this is the crux of your test and needs to be done even if you are not using mock objects.<br />
e.g. if you are unit testing a method of a <a href="http://www.corej2eepatterns.com/Patterns2ndEd/ApplicationService.htm">Service</a> object, at some point you are going to have to call that method in order to test its effect.</p>
<p><a name="5"><br />
<h2>5. Verify the mock was used as expected</h2>
<p></a><br />
The final step is where we ask EasyMock to confirm that all our expectations were met. That is, we ask EasyMock to confirm that a method call corresponding to each expectation we set is actually made. This can be done as either</p>
<pre><code>EasyMock.verify(mock)</code></pre>
<p>or</p>
<pre><code>EasyMock.verifyAll()</code></pre>
<p>Note that this step is not mandatory, but if it is omitted, there will be no verification performed that the expected behavior we specified actually took place. So for example, if you specify</p>
<pre><code>    mock.expectedOperation() </code></pre>
<p>and <code>expectedOperation</code> is never called, the tests will still pass.</p>
<p>If verify() <em>is</em> called, exactly what checks are performed depends on the type of mock object we created in step 1.</p>
<blockquote><p>Note that I personally find the exact behavior of verify to be one more confusing parts of EasyMock. The following is my understanding of it and you should consult the EasyMock documentation (and run some tests yourself) before relying on it!</p></blockquote>
<ul>
<li>EasyMock.createNiceMock() &#8211; As discussed earlier, unexpected method calls are not flagged. Calling verify() on a nice mock simply checks that all your expected methods were called, in any order.</li>
<li>EasyMock.createMock() – On a &#8216;normal&#8217; mock, <em>unexpected</em> method calls will be be flagged (they would result in <code>AssertionError: Unexpected method call</code>) even without the call to verify. I think that the call to verify acts the same way as for a &#8216;nice&#8217; mock&#8217;. That is, EasyMock simply checks that all your <em>expected</em> methods were called, in any order.
<p>[If anyone out there knows of a difference in the effect of calling verify() between a nick mock and a normal mock, I would like to know!]</li>
<li>EasyMock.createStrictMock() – Again, unexpected method calls will be flagged, and the order of the expected method calls is also checked but this time, the order of the expected methods is also checked.</li>
</ul>
<p>Again, with the same disclaimer as before of this being my understanding only, I have tried to summarize the above behavior in the following table:</p>
<table border="1">
<tr>
<td>&nbsp;</td>
<td bgcolor="#FFF380">NiceMock
<p>without verify()</td>
<td bgcolor="#FFF380">NiceMock
<p>with verify()</td>
<td bgcolor="#FBB117">Mock
<p>without verify()</td>
<td bgcolor="#FBB117">Mock
<p>with verify()</td>
<td bgcolor="#F9966B">StrickMock
<p>without verify()</td>
<td bgcolor="#F9966B">StrickMock
<p>with verify()</td>
</tr>
<tr>
<td>Checks for Expectations being met</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FFF380">Y</td>
<td bgcolor="#FBB117">N</td>
<td bgcolor="#FBB117">Y</td>
<td bgcolor="#F9966B">N</td>
<td bgcolor="#F9966B">Y</td>
</tr>
<tr>
<td>Checks for Expectations being met in exact order</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FBB117">N</td>
<td bgcolor="#FBB117">N</td>
<td bgcolor="#F9966B">N</td>
<td bgcolor="#F9966B">Y</td>
</tr>
<tr>
<td>Unexpected methods flagged</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FBB117">Y</td>
<td bgcolor="#FBB117">Y</td>
<td bgcolor="#F9966B">Y</td>
<td bgcolor="#F9966B">Y</td>
</tr>
</table>
</p>
<h2>References</h2>
<p><a href="http://easymock.org/Documentation.html">EasyMock Documentation</a><br />
<a href="http://www.ibm.com/developerworks/java/library/j-easymock/index.html">Easier testing with EasyMock</a></p>
<h2>Links</h2>
<p><a href="http://www.dzone.com/links/r/easymock_facts_and_fallacies.html">EasyMock Facts and Fallacies</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/easymock-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hamcrest Matcher</title>
		<link>http://www.shaunabram.com/hamcrest-matcher/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hamcrest-matcher</link>
		<comments>http://www.shaunabram.com/hamcrest-matcher/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 05:50:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Hamcrest]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[unittesting]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1157</guid>
		<description><![CDATA[As a follow up to the Hamcrest post I made yesterday, I wanted to post an example of my own Hamcrest matcher implementation. This matcher tests if a string contains a specified number of substrings. An example usage could be: String sql = "select a,b,c from tableA"; assertThat(sql, hasNumberOfSubstrings(",", 2)); See the source code below. [...]]]></description>
			<content:encoded><![CDATA[<p>As a follow up to the <a href="http://www.shaunabram.com/hamcrest/">Hamcrest post</a> I made yesterday, I wanted to post an example of my own Hamcrest matcher implementation. This matcher tests if a string contains a specified number of substrings.<br />
An example usage could be:</p>
<pre><code>    String sql = "select a,b,c from tableA";
    assertThat(sql, hasNumberOfSubstrings(",", 2));</code></pre>
<p>See the source code below. I have been reading up on OSS licenses recently and decided to release this using the same license as <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> &#8211; the <a href="http://www.opensource.org/licenses/bsd-license.php">new BSD license</a>.</p>
<p>I have also attached a <a href="http://www.shaunabram.com/HasNumberOfSubStrings_Hamcrest_Matcher.jar">jar</a> which includes the associated unit tests, although you will need the hamcrest-unit-test project to compile, which can be <a href="http://code.google.com/p/hamcrest/downloads/list">downloaded</a> as part of the hamcrest all-in-one jar.<br />
<span id="more-1157"></span> </p>
<pre><code>
package com.shaunabram.hamcrest;

import java.util.regex.Pattern;
import org.hamcrest.*;

/**
 * Matcher which tests if a string contains a specified number of substrings.
 *
 * @author sabram
 */
public class HasNumberOfSubstrings extends TypeSafeMatcher&lt;String&gt; {

    private final String substring;
    private final int count;

    public HasNumberOfSubstrings(String substring, int count) {
        this.substring = substring;
        this.count = count;
    }

    @Override
    protected boolean matchesSafely(String item) {
        Pattern p = Pattern.compile(substring);
        java.util.regex.Matcher m = p.matcher(item);
        int actualCount = 0;
        while (m.find()) {
            actualCount++;
        }
        if (actualCount == count) return true;
        else return false;
    }

    public void describeTo(Description description) {
        description.appendText("String containing ")
            .appendText(count + " occurences of ")
            .appendText(substring);

    }

    @Override
    public void describeMismatchSafely(String item, Description mismatchDescription) {
      mismatchDescription.appendValue(count)
                         .appendText(" occurence(s) of ")
                         .appendValue(substring)
                         .appendText(" in ")
                         .appendText(item);
    }

    @Factory
    public static Matcher&lt;String&gt; hasNumberOfSubstrings(String substring, int count) {
        return new HasNumberOfSubstrings(substring, count);
    }

}

</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/hamcrest-matcher/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hamcrest</title>
		<link>http://www.shaunabram.com/hamcrest/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hamcrest</link>
		<comments>http://www.shaunabram.com/hamcrest/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 03:33:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Hamcrest]]></category>
		<category><![CDATA[JUnit]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1014</guid>
		<description><![CDATA[Hamcrest is a framework for writing matcher objects. Matchers have a variety of uses, but are particularly useful when writing unit tests. Instead of using JUnit&#8217;s assertEquals methods, we use Hamcrest&#8217;s assertThat construct with one (or more) of the many Matchers available. For example assertTrue(a.equalTo(b)); becomes assertThat(a, equalTo(b)); A small change in this example, but [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/hamcrest/wiki/Tutorial">Hamcrest</a> is a framework for writing matcher objects. <a href="http://www.jmock.org/matchers.html">Matchers</a> have a variety of uses, but are particularly useful when writing unit tests. Instead of using JUnit&#8217;s assertEquals methods, we use Hamcrest&#8217;s assertThat construct with one (or more) of the many Matchers available. For example</p>
<pre><code>    assertTrue(a.equalTo(b));</code></pre>
<p>becomes</p>
<pre><code>    assertThat(a, equalTo(b));</code></pre>
<p>A small change in this example, but Hamcrest&#8217;s benefits are many, enabling you to write much more flexible tests that are easier to read and have more meaningful failure messages.<br />
<span id="more-1014"></span><br />
<br/></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#benefits">Benefits of using Hamcrest</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#improvedReadability">Improved readability of tests</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#easierFailure">Better failure messages</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#combineMatcher">Combine Matchers</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#customMatcher">Custom Matchers</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#limitations">Limitations</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#whenNotToUse">Don&#8217;t use if JUnit will do</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#findingMatchers">Finding the right Matcher</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#setup">Setup</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#troubleShooting">Trouble Shooting</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#links">Links</a></p>
<p><a name="benefits"></a><br />
<br/></p>
<h3>Benefits of using Hamcrest</h3>
<p><br/><br />
<a name="improvedReadability"></a></p>
<h4>Improved readability of tests</h4>
<p>The following code, which utilizes the Hamcrest API, is easy to understand, even if you have no understanding of Hamcrest, or Java for that matter:</p>
<pre><code>    assertThat(car, is(equalTo(ferrari));
    assertThat(cars, hasItems(ferarri, porsche));</code></pre>
<p>Basically, Hamcrest provides a <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent API</a>.</p>
<p><a name="easierFailure"></a><br />
<br/></p>
<h4>Better failure messages</h4>
<p>This is one of the biggest advantages of using Hamcrest.<br />
For example, if you run the following test, which makes use of JUnit&#8217;s assertTrue method:</p>
<pre><code>
    @Test
    public void testGreatThan_JUnit() {
        int minimumPrice = 0;
        int actualPrice = -1;
        //using org.junit.Assert.assertTrue
        assertTrue(actualPrice &gt; minimumPrice);
    }</code></pre>
<p>You get the following terse and uninformative error:</p>
<blockquote><p>java.lang.AssertionError</p></blockquote>
<p>However if you rewrite the test to use Hamcrest&#8217;s assertThat method with the greaterThan matcher, as follows:</p>
<pre><code>
    @Test
    public void testGreaterThan_Hamcrest() {
        int minimumPrice = 0;
        int actualPrice = -1;
        //using org.hamcrest.MatcherAssert.assertThat
        //and  org.hamcrest.Matchers.greaterThan
        assertThat(actualPrice, greaterThan(minimumPrice));
    }</code></pre>
<p>You would get the following much more informative error message:</p>
<blockquote><p>
java.lang.AssertionError:<br />
Expected: a value greater than <0><br />
     but: <-1> was less than <0>
</p></blockquote>
<p>Basically, assertThat will tell you what was expected and what the value actually was where as assertTrue will only tell you that you got false where you expected true.<br />
(You can of course put an explicit error message in the JUnit assertion yourself of course, as in:<br />
assertTrue(&#8220;Expected a value greater than &#8221; + minimumPrice, actualPrice > minimumPrice);<br />
But Hamcrest is more descriptive and avoids the extra effort.)</p>
<p><a name="combineMatchers"></a></p>
<h4>Combinations of Matchers</h4>
<p>Hamcrest allows you to use weird and wonderful combinations of Matchers. The obvious example is using not(), but other combinations can be achieved using Matchers such as both(), either(), or(), anyOf(), and many more.</p>
<p><a name="customMatcher"></a></p>
<h4>Create your own Matchers</h4>
<p>You can also create your own custom Matchers too, by implementing the Matcher interface. I wrote a blog post with an <a href="http://www.shaunabram.com/hamcrest-matcher/">example of a custom matcher</a>, but you can also find good examples <a href="http://code.google.com/p/hamcrest/wiki/Tutorial#Writing_custom_matchers">here</a> and <a href="http://blogs.atlassian.com/developer/2009/06/how_hamcrest_can_save_your_sou.html">here</a>.<br />
<br/><br />
Finally, as a wrap up to the benefits of using Hamcrest, see the <a href="http://junit.sourceforge.net/doc/ReleaseNotes4.4.html">JUnit release notes</a> which includes a description of using the Matcher mechanism.<br />
<a name="limitations"></a><br />
<br/></p>
<h3>Limitations</h3>
<p><a name="whenNotToUse"></a><br />
<br/></p>
<h4>Don&#8217;t use if JUnit will do</h4>
<p>If there is already a suitable JUnit method to use, there may not be any benefit to using a Hamcrest Matcher. Specifically, if you are just comparing primitive or String values, JUnit&#8217;s overloaded assertEquals methods should be adequate. For example, the follow two test approaches are both fairly easy to read and give the same message on test failure:</p>
<pre>
<code>	@Test
    	public void testEquals_JUnit() {
	    int expectedPrice = 0;
	    int actualPrice = -1;
	    //using org.junit.Assert.assertEquals
	    assertEquals(expectedPrice, actualPrice);
	    //java.lang.AssertionError: expected:&lt;0&gt; but was:&lt;-1&gt;
	}

	@Test
	public void testEquals_Hamcrest() {
	    int expectedPrice = 0;
	    int actualPrice = -1;
	    //using org.hamcrest.MatcherAssert.assertThat
            //and org.hamcrest.Matchers.equalTo
	    assertThat(actualPrice, equalTo(expectedPrice));
	    //java.lang.AssertionError: Expected: &lt;0&gt; but: was &lt;-1&gt;
	}</code>
</pre>
<p>However, for anything more complicated than primitive or String comparison, Hamcrest&#8217;s Matchers are likely to be much more useful.</p>
<p><a name="findingMatchers"></a><br />
<br/></p>
<h4>Finding the right Matcher</h4>
<p>One of the issues I have with Hamcrest is that the matchers are not all available in one place. It makes finding the correct matcher difficult and also means your IDE&#8217;s code assist, or import organizer, is not likely to be much help either. Most matchers are accessible via the <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/Matchers.html">Matchers</a> class (although confusingly there is also the <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/CoreMatchers.html">CoreMatchers</a> class, which seems to be a subset &#8211; I never quite figured that one out&#8230;). But other matchers are located in other classes and packages.</p>
<p>Example 1<br />
The very useful <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/Matchers.html#hasItem(T)">hasItem</a> matcher is available in the aforementioned Matchers class:</p>
<pre><code>    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.hasItem;

    public class HamcrestExamples {

        List&lt;String&gt; list = new ArrayList&lt;String&gt;();

	@Before
	public void setup() {
		list.add("itemA");
		list.add("itemB");
	}

	@Test
	public void test() {
		assertThat(list, hasItem("itemA"));
	}
}</code></pre>
<p>But if you want to use the very similar <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/core/IsCollectionContaining.html#hasItems%28T...%29">hasItems</a> matcher, you need to know (or trawl the javadocs to find out) it is in the <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/core/IsCollectionContaining.html">IsCollectionContaining</a> class.</p>
<pre><code>    import static org.hamcrest.core.IsCollectionContaining.hasItems;
    ...
        @Test
	public void testHasItems() {
		assertThat(list, hasItems("itemA", "itemB"));
	}</code></pre>
<p>Example 2<br />
There is a useful containsString() method in the Matchers class that returns a Matcher to check is a String contains a sub-String, but if you want to check if a String contains several sub-Strings, in order, you need to know to look at the <a href="http://www.shaunabram.com/hamcrest1.3RC2-javadoc/org/hamcrest/text/StringContainsInOrder.html">StringContainsInOrder</a> class.</p>
<p>Notes: </p>
<ul>
<li>It looks like the above hasItems example will be remedied in 1.3 where hasItems will be made available via the Matchers class.</li>
<li>There is a very similar testing library that seems to overcome this problem called <a href="http://docs.codehaus.org/display/FEST/Fluent+Assertions+Module">Fluent Assertions module</a> from <a href="http://fest.easytesting.org/">FEST</a>. FEST has all the matchers available via a single static import. (Also, see this interesting <a href="http://docs.codehaus.org/display/FEST/Comparing+to+Hamcrest">comparison</a> with Hamcrest  &#8211; I see no reason not to use both)</li>
</ul>
<p><a name="setup"></a><br />
<br/></p>
<h3>Setup</h3>
<ol>
<li>Download the Hamcrest jar(s) from <a href="http://code.google.com/p/hamcrest/downloads">http://code.google.com/p/hamcrest/downloads</a> (using the all-in-one Jar is easiest)<br />
<blockquote><p>Note that JUnit does ship with some Hamcrest classes included. However, I prefer to use the Hamcrest jars directly because</p>
<ul>
<li>JUnit only includes the core Hamcrest (hamcrest-core) API classes. A much larger library of Matcher implementations is available by also using the hamcrest-library jars. Personally, I simply use the hamcrest-all.jar, which includes all the available Hamcrest classes.
</li>
<li>The package names in JUnit are different than those in Hamcrest e.g.  <em>org.hamcrest.MatcherAssert.assertThat</em> versus <em>org.junit.Assert.assertThat</em><br />
I prefer to keep things simply by always referring to the native org.hamcrest packages directly.
</li>
</ul>
<p>If you do choose to use the Hamcrest jars directly, it is also advisable to use the junit-dep jars. These come without the Hamcrest classes included, avoiding any uncertainty about which Hamcrest classes you are actually using.
</p></blockquote>
<li>Add the Hamcrest jar(s) to your classpath or maven dependencies.</li>
<li>Statically import Hamcrest&#8217;s assertThat construct and the Hamcrest matchers:<br />
<blockquote><p>import static org.hamcrest.MatcherAssert.assertThat;<br />
import static org.hamcrest.Matchers.*;</p></blockquote>
</li>
<li>Start using Hamrests&#8217;s assertThat in your unit tests, instead of JUnit&#8217;s assertTrue and assertEquals etc<br />
e.g. instead of</p>
<pre><code>    assertEquals(expectedValue, actualValue);</code></pre>
<p>use</p>
<pre><code>    assertThat(actualValue, equalTo(expectedValue));</code></pre>
</li>
</ol>
<p>Perhaps in future postings I will talk about how to use Hamcrest&#8217;s Matchers with Mock object frameworks such as <a href="http://easymock.org/">EasyMock</a> and <a href="http://www.jmock.org/">JMock</a>.</p>
<p><a name="troubleShooting"></a><br />
<br/></p>
<h3>Trouble Shooting</h3>
<p>Error:</p>
<blockquote><p>java.lang.SecurityException: class &#8220;org.hamcrest.Matchers&#8221;&#8216;s signer information does not match signer information of other classes in the same package</p></blockquote>
<p>You simply need to make sure the Hamcrest jar comes before JUnit in your classpath. Alternatively, use junit-dep.</p>
<p>Error:</p>
<blockquote><pre><code>cannot find symbol method
assertThat(java.util.List&lt;ExampleClass&gt;,org.hamcrest.Matcher&lt;java.lang.Iterable&lt;java.lang.Object&gt;&gt;)</code></pre>
</blockquote>
<p>or</p>
<blockquote><pre><code>cannot find symbol method
assertThat(java.util.List&lt;ExampleClass&gt;,org.hamcrest.Matcher&lt;java.lang.Iterable&lt;? super
java.lang.Object&gt;&gt;)</code></pre>
</blockquote>
<p>This error can happen with any iterable (not just Lists, as in the above example) using hasItem or hasItems (and possibly other matchers too). It is a known issue with Hamcrest at the moment and is documented <a href="http://code.google.com/p/hamcrest/issues/detail?id=84">here</a>, along with some fixes. I took the not-pretty-but-works option of declaring the Matcher in a local variable first<br />
e.g.</p>
<pre><code>    assertThat(list, hasItems(item1, item2));</code></pre>
<p>becomes</p>
<pre><code>    Matcher&lt;java.lang.Iterable&lt;ExampleClass&gt;&gt; matcher = hasItems(item1, item2);
    assertThat(list, matcher);</code></pre>
<p>Like I said, not-pretty-but-works.</p>
<p><a name="links"></a><br />
<br/></p>
<h3>Links</h3>
<ul>
<li><a href="http://code.google.com/p/hamcrest/">Hamcrest home page</a></li>
<li><a href="http://code.google.com/p/hamcrest/wiki/Tutorial">Hamcrest Tutorial</a></li>
<li><a href="http://www.shaunabram.com/hamcrest1.2-javadoc/index.html">Hamcrest API docs</a> &#8211; At the time of writing, the Hamcrest API docs seem surprisingly hard to come by online and there is an <a href="http://code.google.com/p/hamcrest/issues/detail?id=81">ticket</a> for this on the Hamcrest site. There also seems to be <a href="http://code.google.com/p/hamcrest/issues/detail?id=98">some issues</a> when building the javadocs for yourself:<br />
In the mean time, I have taken the liberty of posting them on my site here:</p>
<ul>
<li><a href="http://www.shaunabram.com/hamcrest1.2-javadoc/index.html">Hamcrest 1.2 javadocs</a></li>
<li><a href="http://www.shaunabram.com/hamcrest1.3RC2-javadoc/index.html">Hamcrest 1.3 RC2 javadocs</a></li>
</ul>
<p></a></p>
<li><a href="http://kentbeck.github.com/junit/javadoc/latest/">JUnit API docs</a></li>
<li><a href="http://docs.codehaus.org/display/FEST/Fluent+Assertions+Module">Fluent Assertions module</a> from <a href="http://fest.easytesting.org/">FEST</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/hamcrest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OSCON Day1: Test Driven Database Development</title>
		<link>http://www.shaunabram.com/oscon-day1-tddd/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=oscon-day1-tddd</link>
		<comments>http://www.shaunabram.com/oscon-day1-tddd/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 01:57:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[oscon]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[tddd]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=871</guid>
		<description><![CDATA[The first tutorial at OSCON was on Test Driven Database Development. The idea was to use pgTAP to write unit tests to check database correctness, including table structures, views and stored procedures. As a fan of Test Driven Development (TDD) for regular code, the concept of using it on the database tier makes a lot [...]]]></description>
			<content:encoded><![CDATA[<p>The first tutorial at <a href="http://www.oscon.com/oscon2010">OSCON</a> was on <a href="http://www.oscon.com/oscon2010/public/schedule/detail/14168">Test Driven Database Development</a>. The idea was to use <a href="http://pgtap.org/">pgTAP</a> to write unit tests to check database correctness, including table structures, views and stored procedures. As a fan of Test Driven Development (TDD) for regular code, the concept of using it on the database tier makes a lot of sense.</p>
<p>Unfortunately I had a lot of problems getting the required software setup working, which included <a href="http://www.postgresql.org/">PostgreSQL</a>, <a href="http://pgtap.org/">pgTAP</a>, <a href="http://search.cpan.org/~andya/Test-Harness-3.21/lib/Test/Harness.pm">Test::Harness</a>, <a href="http://www.gnu.org/software/make/">make</a> and <a href="http://www.perl.org/">perl</a>. Ultimately I wasn&#8217;t able to get the examples running due to imcompatabilities between PostgreSQL and pgTAP on my Macbook Pro (OS X 10.5.8) and ended with this error:</p>
<p><code>dyld: Library not loaded: /usr/local/lib/libxml2.2.dylib<br />
  Referenced from: /Library/PostgreSQL/8.4/lib/postgresql/pgxs/src/makefiles/../../src/test/regress/pg_regress<br />
  Reason: Incompatible library version: pg_regress requires version 10.0.0 or later, but libxml2.2.dylib provides version 9.0.0</code></p>
<p>I considered trying to upgrade libxml, but there were <a href="http://superuser.com/questions/132177/os-x-not-booting-after-upgrading-libxml2">suggestions</a> that this could cause my machine to not boot! I even considered upgrading to OS X 10.6 (Snow Leopard), but decided that this was a little too close to shaving yaks.</p>
<p>I would really like to get more familiar with pgTAP at some point, but I will have to put on hold for now&#8230;</p>
<p>Update: I managed to get some input from <a href="http://www.oscon.com/oscon2010/public/schedule/speaker/6582">David Wheeler</a>, worked through the technical issues and got all the tests running. Thanks David! Despite the earlier setup problems, I came away with a very positive feeling about TDDD and pgTAP and can see it playing a part in any future database schema development I do.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/oscon-day1-tddd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selenium talk at SF JUG</title>
		<link>http://www.shaunabram.com/sfjug-selenium/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sfjug-selenium</link>
		<comments>http://www.shaunabram.com/sfjug-selenium/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 07:26:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[JUG]]></category>
		<category><![CDATA[q]]></category>
		<category><![CDATA[selenium]]></category>
		<category><![CDATA[sfjug]]></category>
		<category><![CDATA[unittesting]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=749</guid>
		<description><![CDATA[I attended another great San Francisco JUG meeting tonight, this time on How to use Selenium with Maven/Ant to automate testing of web apps. The talk was given by Chris Bedford, from Build Lackey Labs &#8211; &#8220;Automating the Monkey Work Out and the Quality In!&#8221;. Overall, I thought this was a great talk by Chris. [...]]]></description>
			<content:encoded><![CDATA[<p>I attended another great <a href="http://www.sfjava.org/calendar/10674274/">San Francisco JUG</a> meeting tonight, this time on <a href="http://www.sfjava.org/calendar/11982857/">How to use Selenium with Maven/Ant to automate testing of web apps</a>.</p>
<p>The talk was given by Chris Bedford, from <a href="http://buildlackey.com/">Build Lackey Labs</a> &#8211; &#8220;Automating the Monkey Work Out and the Quality In!&#8221;. Overall, I thought this was a great talk by Chris. He clearly has a huge amount of experience creating automated tests and integrating them with build tools and he gave a well structured, interesting, well delivered presentation. I have posted a copy of <a href="http://www.shaunabram.com/attachments/testing-java-web-apps-with-selenium5.ppt">Chris&#8217;s slides</a> and I think the video will be posted on the SF JUG site at some point, but I have also posted my notes from the presentation below&#8230;<br />
<span id="more-749"></span></p>
<h3>Selenium Overview</h3>
<p>Chris started off with an overview of <a href="http://seleniumhq.org/">Selenium</a> &#8211; a tool for automating tests for web based applications. He then introduced us to the Selenium IDE &#8211; a Firefox add-on that allows you to set up tests by recording clicks on a web page, or by manually entering commands. The tests can then be played back as part of your automated test suite.</p>
<h3>Creating Selenium Tests</h3>
<p>Chris showed us the process by both executing an existing test he had already setup, and by walking us through the creation of a new test, which loaded a page, waited for text to be present, clicked on a link, and confirmed that text was present. The test was a html file, but he showed how to export it as <a href="http://testng.org/doc/index.html">TestNG</a> and <a href="http://www.junit.org/">JUnit</a> tests  (although both exports resulted in kind of ugly java code!)</p>
<h3>Possible hiccups with Selenium</h3>
<p>One of the things I thought Chris did well was, in addition to pointing out all the many great things about Selenium, he also pointed out some of the slight issues with Selenium that he has encountered during his time using it, such as</p>
<ul>
<li>Difficulties getting the initial Open page to work</li>
<li>Issues with where the test files get saved</li>
<li>Making sure you have the tests run slow to start with (to avoid timing/loading issues)</li>
<li>The Selenium IDE may be difficult to get working with IE (Firefox is fine)</li>
</ul>
<h3>Selenium Components</h3>
<p>The main Selenium section then finished up with a quick over of the various Selenium Components:</p>
<ul>
<li>Selenium IDE</li>
<li>Selenese Commands</li>
<li>Selenium RC (Remote Control)</li>
</ul>
<p>Chris also had a section on the &#8216;<a href="http://en.wikipedia.org/wiki/Same_origin_policy">same origin</a>&#8216; JavaScript  policy that Selenium manages to circumvent by using the Selenium RC Server. He managed to explain the issue in simple terms.</p>
<h3>Other functional test alternatives</h3>
<p>Chris discussed other functional test alternatives by comparing <a href="http://webtest.canoo.com/webtest/manual/WebTestHome.html">Canoo</a> to Selenium (Canoo is also an automated web app testing framework).</p>
<p>Chris also mentionted <a href="http://code.google.com/p/umangite/">Umangite</a>, Chris Richardson&#8217;s open source testing framework that makes Selenium tests easier to write. I have used this before, and agree it is worth checking out&#8230;</p>
<h3>Using Selenium with Build Tools</h3>
<p>He then discussed using Maven with Selenium, including using <a href="http://cargo.codehaus.org/">Cargo</a> (e.g. using the <a href="http://cargo.codehaus.org/Maven2+plugin">cargo maven2 plugin</a>). Cargo is a set of APIs that assists in</p>
<ul>
<li>installing web containers, such as Tomcat, JBoss</li>
<li>booting and shutting them down</li>
<li>deploying web apps (.wars, .ears)</li>
</ul>
<p>Chris finished the Selenium &#038; build tools section with a quick run through of using Selenium with <a href="http://ant.apache.org/">Ant</a>.</p>
<h4>Continuous Integration</h4>
<p>The final section of the presentation was a talk on Continuous Integration (CI). Chris described CI as: </p>
<ul>
<li>A dedicated box (see my follow up question below!) that runs regular full builds (including tests) of your software</li>
<li>Build triggers when any developer checks into SCM</li>
<li>Team is notified of any issues</li>
</ul>
<p>And talked about how Selenium can be used with <a href="http://hudson-ci.org/">Hudson</a> &#8211; a very cool CI tool from Sun. This leads well into <a href="http://www.sfjava.org/calendar/12296161/">next month&#8217;s SF JUG talk</a>!</p>
<h3>Q&#038;A</h3>
<p>Q: Do you have any info on WebDriver merging with Selenium?<br />
A: No, but sounds interesting!</p>
<p>Q: How closely do test writers work with marketing people?<br />
A: Chris suggested checking out the <a href="http://www.easyb.org/">easyb</a> framework, a behavior driven development framework that allows you to write conditions in a very abstract level, using a DSL that marketers can use and understand. He also suggested looking at the <a href="http://www.fitnesse.org/">fitnesse</a> framework.</p>
<p>Q: I asked Chris via email after the talk what he meant by needing &#8216;dedicated&#8217; box/server for Continuous Integration.<br />
A: He clarified that by &#8216;dedicated&#8217;, he just meant that the build box  should not be a box that you are doing development on, and that there isn&#8217;t anything wrong with having a mix of services on one machine. e.g. having a qa box that has the CI server and maybe hosts the bug tracking system as well&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/sfjug-selenium/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Groovy: Cool but slow</title>
		<link>http://www.shaunabram.com/groovy-slow/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=groovy-slow</link>
		<comments>http://www.shaunabram.com/groovy-slow/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 07:44:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=576</guid>
		<description><![CDATA[I have been learning Groovy recently (as part of Project Euler, a series of Maths programming problems). For the most part, I love it. I particularly like the easy syntax. Java without the crud! e.g. System.out.println becomes simply println for (int i-0; i&#60;10; i++) becomes for ( i in 0..9 ) Accessor methods are autogenerated [...]]]></description>
			<content:encoded><![CDATA[<p>I have been learning <a href="http://groovy.codehaus.org/">Groovy</a> recently (as part of <a href="http://projecteuler.net/">Project Euler</a>, a series of Maths programming problems). For the most part, I love it. I particularly like<br />
the easy syntax. Java without the crud!<br />
 e.g. </p>
<ul>
<li><code>System.out.println</code> becomes simply <code>println</code></li>
<li><code>for (int i-0; i&lt;10; i++)</code> becomes <code>for ( i in 0..9 )</code></li>
<li>Accessor methods are autogenerated and used</li>
</ul>
<p>Sure, the <a href="http://java.dzone.com/news/which-ide-supports-groovy-best">poor IDE support</a> is a little annoying, especially the lack luster code completion and debugging capabilities, but I am sure it will improve soon (especially with SpringSource <a href="http://broadcast.oreilly.com/2008/11/springsource-getting-into-the.html">on the case</a>).</p>
<p>But then I started to notice some slowness when using it. So, I performed a simple performance comparison and the results shocked me.<br />
I wrote an identical loop in both Java and Groovy (see the code below) which simply loops a million times.</p>
<ul>
<li>The Java version took ~5ms</li>
<li>The Groovy version took ~500ms</li>
</ul>
<p>I was shocked! Could Groovy really be a 100 times slower? I had heard rumors about Groovy being a bit slower than Java, but I hadn&#8217;t expected it to be this dramatic. Surely this is drastic enough to stop Groovy being used in serious, production quality projects?</p>
<p>I discussed this with a friend who is a Groovy advocate. He made the following points:</p>
<blockquote><p>1. I was running with an older, slower version of Groovy</p></blockquote>
<p>This is true. I ran the tests in Eclipse 3.5, with v1 of the Eclipse Groovy plugin, which uses v1.5.7 of the Groovy compiler.<br />
However, when I downloaded the latest version of Groovy (Version: 1.6.3 with JVM: 1.6.0_13) and ran from the command line, it still took the Groovy code ~200 ms. A huge improvement, but still ~40 times slower than Java.</p>
<blockquote><p>
2. It is an artificial, unrealistic test, as these kind of huge loops are not normal in most programs</p></blockquote>
<p>This is also true. But although artificial, it is still a straight comparison. Also, these kind of loops aren&#8217;t so unusual in Project Euler type problems (at least in my crude brute force solutions!). </p>
<p>There are also some more detailed Java/Groovy performance test results <a href="http://www.christianschenk.org/blog/performance-comparison-between-groovy-and-java/">here</a> and <a href="http://www.javalobby.org/java/forums/t101256.html">here</a>. </p>
<p>So, overall, I think the performance is a big issue. But not enough to stop me using it for pet projects. I am even going to keep trying to use it for Project Euler &#8211; it will be more motivation to avoid the brute force solutions. It is however, enough to stop me using it in any serious production apps. </p>
<p>For the record, here is the exact code I ran:<br />
Java version</p>
<pre>
<code>		long max = 1000000;
		long start = Calendar.getInstance().getTimeInMillis();
		for(int i=0;i&lt;max; i++) {}
		long end = Calendar.getInstance().getTimeInMillis();
		long duration = end - start;
		System.out.println(duration);</code>
</pre>
<p>Groovy version</p>
<pre>
<code>		long max = 1000000;
		long start = Calendar.getInstance().getTimeInMillis();
		for(int i=0;i&lt;max; i++) {}
		long end = Calendar.getInstance().getTimeInMillis();
		long duration = end - start;
		println(duration);  </code>
</pre>
<p>It is also worth pointing out that when I changed the Groovy code to use proper Groovy syntax, as in <code>for (i in 1..1000000) </code> is was substantially faster (although still significantly slower than Java), but I have left it as is, for a apples vs apples comparison.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/groovy-slow/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Exceptions versus Return Values</title>
		<link>http://www.shaunabram.com/exceptions-vs-return-values/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=exceptions-vs-return-values</link>
		<comments>http://www.shaunabram.com/exceptions-vs-return-values/#comments</comments>
		<pubDate>Mon, 16 Mar 2009 16:57:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[exceptions]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=171</guid>
		<description><![CDATA[In a previous post here, I blogged about checked exceptions and how I felt they are a useful tool in your Java toolbox. It is generally accepted that errors, or unrecoverable events, should be dealt with using unchecked exceptions and that recoverable problems, or contingencies, should be dealt with using checked exceptions. However, there is [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous post <a href="http://www.shaunabram.com/checked-exceptions/">here</a>, I blogged about checked exceptions and how I felt they are a useful tool in your Java toolbox. It is generally accepted that errors, or unrecoverable events, should be dealt with using unchecked exceptions and that recoverable problems, or contingencies, should be dealt with using checked exceptions.</p>
<p>However, there is another option for dealing with recoverable problems, i.e. using return values.</p>
<p><a href="http://www.shaunabram.com/exceptions-vs-return-values-article/">Read full article &amp; Comments</a></p>
<p><span id="sample-permalink"><br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/exceptions-vs-return-values/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Checked Exceptions</title>
		<link>http://www.shaunabram.com/checked-exceptions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=checked-exceptions</link>
		<comments>http://www.shaunabram.com/checked-exceptions/#comments</comments>
		<pubDate>Mon, 16 Mar 2009 16:41:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[exceptions]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=163</guid>
		<description><![CDATA[The use of checked exceptions in Java is still widely debated. This post contains thoughts on their use by Java experts such as James Gosling, Joshua Bloch (Effective Java) and Bruce Eckel (Thinking in Java), before countering some of the arguments against their use, such as how I don&#8217;t believe they break encapsulation, and that [...]]]></description>
			<content:encoded><![CDATA[<p>The use of checked exceptions in Java is still widely debated. This post contains thoughts on their use by Java experts such as James Gosling, Joshua Bloch (Effective Java) and Bruce Eckel (Thinking in Java), before countering some of the arguments against their use, such as how I don&#8217;t believe they break encapsulation, and that their use shouldn&#8217;t be limited to truly exceptional conditions. It finishes by looking at when alternatives to checked exceptions should be used. The overall slant of the article is that there are many reasons why Exceptions, including checked Exceptions, should still be a part of your Java arsenal.</p>
<p><a href="http://www.shaunabram.com/checked-exceptions-article">Read full article</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/checked-exceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running Hibernate unit tests with Maven</title>
		<link>http://www.shaunabram.com/hibernate-maven-unit-tests/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hibernate-maven-unit-tests</link>
		<comments>http://www.shaunabram.com/hibernate-maven-unit-tests/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 08:37:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Maven]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=42</guid>
		<description><![CDATA[I recently converted a project I have been working on to use Maven. After setting up all the dependencies in the pom, I got everything compiling fine but ran into problems getting the unit tests to pick up the hibernate config (hibernate.cfg.xml) and hibernate mapping (*.hbm.xml) files. With hindsight, it is straightforward, but it took [...]]]></description>
			<content:encoded><![CDATA[<p>I recently converted a project I have been working on to use <a href="http://maven.apache.org/">Maven</a>. After setting up all the dependencies in the pom, I got everything compiling fine but ran into problems getting the unit tests to pick up the hibernate config (hibernate.cfg.xml) and hibernate mapping (*.hbm.xml) files. With hindsight, it is straightforward, but it took me a while to figure it out so I thought I&#8217;d post the solution here.</p>
<p>Initially, I had my hibernate.cfg.xml file in the following directory</p>
<p style="padding-left: 30px;">my-app/src/main/java</p>
<p>And when I first tried to run my hibernate unit tests (mvn test), I got this error:</p>
<p style="padding-left: 30px;">SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found</p>
<p>Some checking of the maven docs and some forums revealed the following possible solutions:<br />
1) Copy the hibernate.cfg.xml file to</p>
<p style="padding-left: 30px;">my-app/target/classes</p>
<p>This works, however I think it is a hack as the target folder is generated rather than being somewhere you should actually manually create files.<br />
2) The next solution I found suggested moving the hibernate.cfg.xml to</p>
<p style="padding-left: 30px;">my-app/src/main/resources</p>
<p>This works well as the contents of this folder are copied to the base level of the my-app/target/classes folder so it is basically a &#8216;more correct&#8217; solution than the first.<br />
3) The next and I think best solution was to create a new, duplicate hibernate.cfg.xml inside</p>
<p style="padding-left: 30px;">my-app/src/test/resources</p>
<p>This allows a different hibernate.cfg.xml file to be used for testing and, for example, facilitates connecting to a different database (such as <a href="http://hsqldb.org/">hsqldb</a>) for testing while continuing to use your regular database (such as <a href="http://www.mysql.com/">MySQL</a>) for the app itself.</p>
<p>A couple of points to note:</p>
<p>1) The hibernate mapping files (i.e. the *.hbm.xml files) should also be in the resources folder (in whatever directory structure you choose) to ensure that these too are accessible by the unit tests.</p>
<p>2) I am not (yet) using Spring with the hibernate components, which would likely have changed the above setup.</p>
<p>Refs/links</p>
<p style="padding-left: 30px;"><a href="http://maven.apache.org/guides/getting-started/index.html#How_do_I_add_resources_to_my_JAR">http://maven.apache.org/guides/getting-started/index.html#How_do_I_add_resources_to_my_JAR</a></p>
<p style="padding-left: 30px;"><a href="http://www.mail-archive.com/users@maven.apache.org/msg54720.html">http://www.mail-archive.com/users@maven.apache.org/msg54720.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/hibernate-maven-unit-tests/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

