<?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>Smartkey - Java Software Consultancy &#187; Test</title>
	<atom:link href="http://blog.smartkey.co.uk/tag/test/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smartkey.co.uk</link>
	<description></description>
	<lastBuildDate>Tue, 13 Dec 2011 15:03:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using Mockito to Unit Test Java Applications</title>
		<link>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/</link>
		<comments>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 18:39:26 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Tool support]]></category>
		<category><![CDATA[Google Code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=604</guid>
		<description><![CDATA[If you&#8217;ve spent any time writing unit tests then you&#8217;ll know that it&#8217;s not always straight-forward. Certain things are inherently hard to test. In this post I&#8217;ll show you the basic principles of creating mock objects with a little help from the Mockito mocking tool.
One common problem faced when unit testing is how to test [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve spent any time writing unit tests then you&#8217;ll know that it&#8217;s not always straight-forward. Certain things are inherently hard to test. In this post I&#8217;ll show you the basic principles of creating mock objects with a little help from the <a href="http://www.mockito.org">Mockito</a> mocking tool.</p>
<p>One common problem faced when unit testing is how to test one object when it is dependant on another object. You could create instances of both the object under test and the dependent object and test them both together, however testing aggregated objects is not what unit testing is about &#8211; unit tests should test individual objects for their correct behaviour, not aggregations of objects! Moreover, this approach just won&#8217;t work if the dependent object hasn&#8217;t even been implemented yet.</p>
<p>A common technique for handling dependencies in unit tests is to provide a surrogate, or &#8220;mock&#8221; object, for the dependent object instead of a real one. The mock object will implement a simplified version of the real objects methods that return predictable results and can be used for testing purposes. </p>
<p>The drawback of this approach is that in a complex application, you could find yourself creating a lot of mock objects. This is where frameworks like Mockito can save you a lot of time and effort.</p>
<h3>A Test Scenario</h3>
<p>To demonstrate what you can do with Mockito, we&#8217;ll examine how we might test an Account object that is dependant on a data access object (AccountDAO).  The account object can calculate the charges applicable in the current month by using the DAO to count the number of days overdrawn and then performing a simple calculation on the value obtained from that call. The method names on the classes we&#8217;ll use are self-explanatory:</p>
<p><img src="http://blog.smartkey.co.uk/wp-content/uploads/2010/02/AccountAndDAO1.png" alt="AccountAndDAO" title="AccountAndDAO" width="376" height="55" class="aligncenter size-full wp-image-648" /><br />
To test this thoroughly, we should test two things:</p>
<ol>
<li>that the account obtains the number of overdrawn days by calling the correct method on the DAO,</li>
<li>that the account calculates the correct fees based upon the value it gets back from the call.</li>
</ol>
<h3>Testing that the account calls the correct method on the DAO</h3>
<p>Using JUnit to run the test case, we could write something like this:</p>
<pre class="brush: java">
import static org.mockito.Mockito.*;

public class TestAccount {
    @Test
    public void checkAccountCallsDaoMethods() {
        //create the object under test
        Account account = new Account();

        //create a mock DAO
        AccountDAO mockedDao = mock(AccountDAO.class);	

        //associate the mocked DAO with the object under test
        account.setDAO(dao);

        //call the method under test
        long charge = account.calculateCharges();

        //verify that the &#039;countOverdrawnDaysThisMonth&#039; was called
        verify(mockedDao).countOverdrawnDaysThisMonth();
    }
}
</pre>
<p>Taking centre stage in all this is the Mockito class which has a bunch of static methods that are used within the unit test (note the static import on line 1). </p>
<p>The call to the &#8216;mock&#8217; method (line 10) creates a mock object that can be used in place of a real AccountDAO. The call to &#8216;verify&#8217; (line 19), will throw an exception if the &#8216;countOverdrawnDaysThisMonth&#8217; method was not called on the mock object. </p>
<p>It is worth noting here that this is a simple example which just demonstrates the basic principle of verification, it is also possible to use the verify method to check for parameter values and ranges in the method call too.</p>
<h3>Testing that the account performs its calculations correctly</h3>
<p>In the above example, we mocked the DAO but didn&#8217;t specify what any of the mocked methods should do. In this case, all methods will return sensible default values of: null, zero or false. More commonly we need to specify something other than these defaults when writing our tests:</p>
<pre class="brush: java">
import static org.mockito.Mockito.*;
import static junit.framework.Assert.*;
import org.junit.*;

public class TestAccount {
    private Account account;

    @Before
    public void setup() {
        AccountDAO mockedDao = mock(AccountDAO.class);

    	//specify that this method on the mock object should return 8
        when(mockedDao.countOverdrawnDaysThisMonth()).thenReturn(8);

        account = new Account();
        account.setDAO(dao);
    }

    @Test
    public void checkChargesWhenOverdrawn() {
        //call the method under test
        long charge = account.calculateCharges();

        //assert that the charge was £2 per day overdrawn
        assertEquals(charge, 16);
    }
}
</pre>
<p>The statement on line 18 specifies that whenever the &#8216;countOverdrawnDaysThisMonth&#8217; is called it should return a value of 8; overriding the default of zero.</p>
<p>Given that the correct charge is two pounds (or dollars) per day overdrawn, then the assertion on line 25 will pass if the account performed the correct calculation (8 x 2 = 16 right).</p>
<h3>Comments</h3>
<p>There&#8217;s loads more to Mockito than we&#8217;ve looked at here. It&#8217;s a neat testing tool that works great with JUnit or TestNG. I&#8217;ve found that it&#8217;s small enough to learn quickly and capable enough to be really useful. Give it a go and write a comment below to let me know what you think of it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

