<?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>lstierneyltd &#187; testing</title>
	<atom:link href="http://lstierneyltd.com/blog/tag/testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://lstierneyltd.com/blog</link>
	<description>Yet another development blog</description>
	<lastBuildDate>Wed, 13 Jul 2011 12:55:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>Unit Test Private Java Methods using Reflection</title>
		<link>http://lstierneyltd.com/blog/development/unit-test-private-java-methods-using-reflection/</link>
		<comments>http://lstierneyltd.com/blog/development/unit-test-private-java-methods-using-reflection/#comments</comments>
		<pubDate>Thu, 05 May 2011 17:02:06 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[How to's]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=254</guid>
		<description><![CDATA[Introduction I realise that the thought of Unit Testing private methods in Java classes can be like a red rag to a bull for some people and I understand the arguments. Therefore, I present the following as a &#8220;how to&#8221;, not a moral argument for or against! Example The class under test The (Reflection Based) [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>I realise that the thought of Unit Testing private methods in Java classes can be like a red rag to a bull for some people and I understand the arguments.</p>
<p>Therefore, I present the following as a &#8220;how to&#8221;, not a moral argument for or against!</p>
<h3>Example</h3>
<h4>The class under test</h4>
<pre class="brush: java; title: ; notranslate">
public class Product() {
    private String privateMethod(String id) {
    //Do something private
    return &quot;product_&quot; + id;
  }
}
</pre>
<h4>The (Reflection Based) Unit Test</h4>
<pre class="brush: java; title: ; notranslate">
import java.lang.reflect.Method;

import static org.junit.Assert.*;
import org.junit.Test;

public class ProductTest {
    private Product product; // the class under test
    private Method m;
    private static String METHOD_NAME = &quot;privateMethod&quot;;
    private Class[] parameterTypes;
    private Object[] parameters;

    @Before
    public void setUp() throws Exception {
        product = new Product();
        parameterTypes = new Class[1];
        parameterTypes[0] = java.lang.String.class;
        m = product.getClass().getDeclaredMethod(METHOD_NAME, parameterTypes);
        m.setAccessible(true);
        parameters = new Object[1];
    }

    @Test
    public void testPrivateMethod() throws Exception {
        parameters[0] = &quot;someIdentifier&quot;;
        String result = (String) m.invoke(product, parameters); 

        //Do your assertions
        assertNotNull(result);
    }
}
</pre>
<h3>Update</h3>
<p>I&#8217;ve since been told that if <a href="http://code.google.com/p/dp4j/" target="_blank">dp4j.jar</a> is in the classpath at compile-time, it will inject the necessary reflection to make this work. I haven&#8217;t had time to try this yet so YMMV.</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/unit-test-private-java-methods-using-reflection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Validation in Annotation Based Validating Spring Beans</title>
		<link>http://lstierneyltd.com/blog/development/examples/spring-examples/unit-testing-validation-in-annotation-based-validating-spring-beans/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/spring-examples/unit-testing-validation-in-annotation-based-validating-spring-beans/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 08:57:07 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=245</guid>
		<description><![CDATA[Motivation I added validation, via annotations, to a Spring &#8220;Model&#8221; bean. I needed someway to Unit Test this validation, without running the container and without initialising the Spring context. The bean (simplified) The Unit Test More It actually took me a few hours to work the above test out (simple as it is). If I [...]]]></description>
			<content:encoded><![CDATA[<h3>Motivation</h3>
<p>I added validation, via annotations, to a Spring &#8220;Model&#8221; bean. I needed someway to Unit Test this validation, <em>without</em> running the container and <em>without</em> initialising the Spring context.</p>
<h3>The bean (simplified)</h3>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public final class ProductModel {

    @NotNull
    @Size(max=100)
    @Pattern(regexp=&quot;[^\n^\t^\r]+&quot;, message=&quot;Long Name must not contain New Lines, Carriage Returns or Tabs&quot;)
    private String longName;

    @Size(max=20)
    private String shortName;

    // rest snipped for brevity
}
</pre>
<h3>The Unit Test</h3>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import java.util.Set;

import javax.validation.ConstraintViolation;

import junit.framework.Assert;

import org.hibernate.validator.HibernateValidator;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

public class Temp {
    private LocalValidatorFactoryBean localValidatorFactory;

    @Before
    public void setup() {
        localValidatorFactory = new LocalValidatorFactoryBean();
        localValidatorFactory.setProviderClass(HibernateValidator.class);
        localValidatorFactory.afterPropertiesSet();
    }
    @Test
    public void testLongNameWithInvalidCharCausesValidationError() {
        final ProductModel productModel = new ProductModel();
        productModel.setLongName(&quot;A long name with\t a Tab character&quot;);
    	Set&lt;ConstraintViolation&lt;ProductModel&gt;&gt; constraintViolations = localValidatorFactory.validate(productModel);
    	Assert.assertTrue(&quot;Expected validation error not found&quot;, constraintViolations.size() == 1);
    }
}
</pre>
<h3>More</h3>
<p>It actually took me a few hours to work the above test out (simple as it is). If I hadn&#8217;t stumbled upon <a href="https://src.springsource.org/svn/spring-framework/trunk/org.springframework.context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java">these Spring Unit Tests</a>, I might never have got it.</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/spring-examples/unit-testing-validation-in-annotation-based-validating-spring-beans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EasyMock Capture Example</title>
		<link>http://lstierneyltd.com/blog/development/easymock-capture-example/</link>
		<comments>http://lstierneyltd.com/blog/development/easymock-capture-example/#comments</comments>
		<pubDate>Thu, 02 Sep 2010 09:46:50 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Examples]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=184</guid>
		<description><![CDATA[Background EasyMock version 2.4 introduced some new functionality &#8211; the ability to capture the arguments passed to mock objects. As ever a few lines of code speaks volumes. Capture Example Test Class Source code for classes under test after the break&#8230;&#8230;. Service Interface Service Implementation Dao Interface Dao Implementation Domain Object (Bean)]]></description>
			<content:encoded><![CDATA[<h4>Background</h4>
<p>EasyMock version 2.4 introduced some new functionality &#8211; the ability to <em>capture</em> the arguments passed to mock objects. As ever a few lines of code speaks volumes.</p>
<h4>Capture Example</h4>
<p><strong>Test Class</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import static org.junit.Assert.assertEquals;

import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Before;
import org.junit.Test;

public class TestServiceImpl {
    private Service service;
    private Dao dao;
    private IMocksControl controller;
    private final String description = &quot;description&quot;;

    @Before
    public void setUp() throws Exception {
        controller = EasyMock.createStrictControl();
        dao = controller.createMock(Dao.class);
        service = new ServiceImpl();
        service.setDao(dao);
    }
    @Test
    public void testSave() {
        Capture &lt;DomainObject&gt; capturedArgument = new Capture &lt;DomainObject&gt;();
        dao.save(EasyMock.and(EasyMock.capture(capturedArgument), EasyMock.isA(DomainObject.class)));
        controller.replay();
        service.save(description);
        controller.verify();
        DomainObject record = capturedArgument.getValue();
        assertEquals(description, record.getDescription());
        assertEquals(&quot;getNextId&quot;, record.getId());
    }
}
</pre>
<p>Source code for classes under test after the break&#8230;&#8230;.<br />
<code><span id="more-184"></span></code><br />
<strong>Service Interface</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public interface Service {
    void save(String description);
    void setDao(Dao dao);
}
</pre>
<p><strong>Service Implementation</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public class ServiceImpl implements Service {
    private Dao dao;

    public void save(String description) {
        DomainObject record = new DomainObject();
        record.setDescription(description);
        record.setId(&quot;getNextId&quot;);
        dao.save(record);
    }
    public void setDao(Dao dao) {
        this.dao = dao;
    }
}
</pre>
<p><strong>Dao Interface</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public interface Dao {
    public abstract void save(DomainObject record);
}
</pre>
<p><strong>Dao Implementation</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public class DaoImpl implements Dao {
    public void save(DomainObject record) {
        // do something
    }
}
</pre>
<p><strong>Domain Object (Bean)</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public class DomainObject {
    private String id;
    private String description;
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/easymock-capture-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selenium Tests Randomly Failing</title>
		<link>http://lstierneyltd.com/blog/development/tips/selenium-tests-randomly-failing/</link>
		<comments>http://lstierneyltd.com/blog/development/tips/selenium-tests-randomly-failing/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 09:10:43 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[selenium]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=178</guid>
		<description><![CDATA[The Problem The project I&#8217;m currently working on uses a lot of selenium tests to verify the behaviour of the web front end and, I must say, I&#8217;ve been quite impressed with it. Yesterday however after updating my local machine with the latest copy of the project from Clearcase I noticed a lot of failing [...]]]></description>
			<content:encoded><![CDATA[<h4>The Problem</h4>
<p>The project I&#8217;m currently working on uses a lot of <a href="http://seleniumhq.org/" target="_blank">selenium tests</a> to verify the behaviour of the web front end and, I must say, I&#8217;ve been quite impressed with it.</p>
<p>Yesterday however after updating my local machine with the latest copy of the project from Clearcase I noticed a lot of failing tests; the worrying (interesting?) thing though was that the failures appeared to be &#8220;random&#8221;. Tests were passing one run and failing the next, with no changes having being made in the source code and no changes in the initial starting conditions. I was starting to pull my hair out. Curiously the tests ran fine on my colleagues&#8217; and the build machine. My workmate had a look (remember the tests ran fine for him) but he too was getting the random failures on my machine &#8211; we were both stumped.<br />
<code><span id="more-178"></span></code></p>
<p>He did unknowingly hit on the problem when he said &#8220;Your machine is a lot zippier than mine&#8221;. After another hour or so the problem and solution became obvious.</p>
<h4>Cause</h4>
<p>The Selenium remote control was executing the steps of the test faster than my local app server and Firefox could keep up. In other words it was trying to verify elements on the page before they had rendered.</p>
<h4>Solution</h4>
<p>To quickly check my hypothesis I ran the Selenium Tests in &#8220;slow mode&#8221; &#8211; all the tests passed!</p>
<p>Now, going forward, I will need to check the test source for all snippets like</p>
<pre class="brush: plain; title: ; notranslate">
browser.click(&quot;someButton&quot;); // causes page to load
verifyTrue(browser.isTextPresent(&quot;someText&quot;));
</pre>
<p>and change them to</p>
<pre class="brush: plain; title: ; notranslate">
browser.click(&quot;someButton&quot;);
browser.waitForPageToLoad(&quot;30000&quot;);
verifyTrue(browser.isTextPresent(&quot;someText&quot;));
</pre>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/tips/selenium-tests-randomly-failing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Spring apps with @RunWith(SpringJUnit4ClassRunner.class)</title>
		<link>http://lstierneyltd.com/blog/development/examples/unit-testing-spring-apps-with-runwithspringjunit4classrunner-class/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/unit-testing-spring-apps-with-runwithspringjunit4classrunner-class/#comments</comments>
		<pubDate>Thu, 24 Jun 2010 11:13:15 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=153</guid>
		<description><![CDATA[The Problem I love Spring, who doesn&#8217;t? One thing however that I found, until recently, a bit awkward was Unit Testing objects which were constructed and initiated via the Spring context and injected into other objects that consumed them. I have seen and used many and varied &#8220;bespoke&#8221; ways to do this, none of which [...]]]></description>
			<content:encoded><![CDATA[<h4>The Problem</h4>
<p>I love <a href="http://www.springsource.org/" target="_blank">Spring</a>, who doesn&#8217;t?</p>
<p>One thing however that I found, until recently, a bit awkward was Unit Testing objects which were constructed and initiated via the Spring context and injected into other objects that consumed them. I have seen and used many and varied &#8220;bespoke&#8221; ways to do this, none of which I found satisfying.</p>
<p>This was until a <a href="http://andrew.montheheids.com" target="_blank">collegue</a> introduced me to the wonder that is <a href="http://static.springsource.org/spring/docs/2.5.x/reference/testing.html" target="_blank">SpringJUnit4ClassRunner</a>. I know, I know, I should have been aware of this ages ago but as they say on millionaire &#8220;it&#8217;s easy if you know the answer&#8221;!<br />
<code><span id="more-153"></span></code></p>
<h4>Solution</h4>
<p>A few lines of code speaks more than a thousand words from me&#8230;&#8230;</p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={&quot;daos.xml&quot;})
public final class DaoTests {

    @Autowired
    private MyDao dao;

    @Test
    public void testLoadTitle() throws Exception {
        String result = dao.doSomething();
        assertNotNull(result);
    }
}
</pre>
<h4>Whats going on?</h4>
<p><strong><em>@RunWith(SpringJUnit4ClassRunner.class)</em></strong><br />
Quoting the docs: &#8220;SpringJUnit4ClassRunner is a custom extension of JUnit4ClassRunner which provides functionality of the Spring TestContext Framework to standard JUnit 4.4+ tests by means of the TestContextManager and associated support classes and annotations.&#8221;</p>
<p>Basically this means that tests are going to be able to get hold of instantiated beans as defined in the Spring context files (see below).</p>
<p><strong><em>@ContextConfiguration(locations={&#8220;daos.xml&#8221;})</em></strong><br />
This is telling the test where to get the context files containing the bean definitions. Note that if you do not provide any arguments to the annotation then a default will be looked for.</p>
<p>For example: If your class is named foo.bar.DaoTests, the context loader will attempt to load your application context from &#8220;classpath:/foo/bar/DaoTests-context.xml&#8221;.</p>
<p><strong><em>@Autowired</em></strong><br />
This will autowire BY TYPE, beans found in the context. Alternatively you could use @Resource to inject the dependencies by NAME (useful if several beans are of the same type)</p>
<h4>Conclusion</h4>
<p>Now it&#8217;s simply the case of adding a few annotations and a few imports to be able easily write tests which use Spring beans. All in all, a very unobtrusive (and fast) process.</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/unit-testing-spring-apps-with-runwithspringjunit4classrunner-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JUnit 4 Test Class with annotations</title>
		<link>http://lstierneyltd.com/blog/development/examples/junit-4-test-class-with-annotations/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/junit-4-test-class-with-annotations/#comments</comments>
		<pubDate>Tue, 08 Jun 2010 11:15:05 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=139</guid>
		<description><![CDATA[A simple example of a JUnit 4 Test class marked up with annotations. Points of note The static import of org.junit.Assert.*]]></description>
			<content:encoded><![CDATA[<p>A simple example of a JUnit 4 Test class marked up with annotations.<br />
<code><span id="more-139"></span></code></p>
<pre class="brush: plain; title: ; notranslate">
import org.junit.*;
import static org.junit.Assert.*; 

public class SampleTest {
    private java.util.List emptyList; 

    /**
     * Sets up the test fixture.
     * (Called before every test case method.)
     */
    @Before
    public void setUp() {
        emptyList = new java.util.ArrayList();
    } 

    /**
     * Tears down the test fixture.
     * (Called after every test case method.)
     */
    @After
    public void tearDown() {
        emptyList = null;
    } 

    @Test
    public void testSomeBehavior() {
        assertEquals(&quot;Empty list should have 0 elements&quot;, 0, emptyList.size());
    } 

    @Test(expected=IndexOutOfBoundsException.class)
    public void testForException() {
        Object o = emptyList.get(0);
    }
}
</pre>
<h4>Points of note</h4>
<p>The <em>static</em> import of org.junit.Assert.*</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/junit-4-test-class-with-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

