<?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>Turnleaf Design &#187; Testing</title>
	<atom:link href="http://www.turnleafdesign.com/tag/testing/feed" rel="self" type="application/rss+xml" />
	<link>http://www.turnleafdesign.com</link>
	<description>Ramblings of a junior developer</description>
	<lastBuildDate>Wed, 11 Nov 2009 05:56:28 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Mocking JDBC Connections with MockRunner</title>
		<link>http://www.turnleafdesign.com/mocking-jdbc-connections-with-mockrunner</link>
		<comments>http://www.turnleafdesign.com/mocking-jdbc-connections-with-mockrunner#comments</comments>
		<pubDate>Wed, 11 Nov 2009 05:54:11 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Mock]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=285</guid>
		<description><![CDATA[Last week I published an article, An Intro into Test Driven Development with Junit4, which got somewhat mixed reviews. One particular commenter on reddit suggested I didn't understand that unit tests shouldn't talk to its data source. I decided to do some investigating into his claims, you can check out my findings here. I was [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fmocking-jdbc-connections-with-mockrunner"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fmocking-jdbc-connections-with-mockrunner" height="61" width="51" /></a></div><p>Last week I published an article, <a href="  http://www.turnleafdesign.com/an-intro-into-test-driven-development-with-junit4" target="_blank">An Intro into Test Driven Development with Junit4</a>, which got somewhat mixed reviews. One particular commenter on reddit suggested I didn't understand that unit tests <a href="http://www.reddit.com/r/programming/comments/9yq8p/an_intro_into_test_driven_development_with_junit4/c0f29uc" target="_blank">shouldn't talk to its data source</a>. I decided to do some investigating into his claims, you can check out my findings <a href="http://www.turnleafdesign.com/ramblings-should-unit-tests-talk-to-a-data-source" target="_blank">here</a>. I was however intrigued none the less and started looking for a tool that would allow me to easily mock a JDBC connection. I found <a href="http://mockrunner.sourceforge.net/" target="_blank">Mockrunner</a> to be the easiest to use of the ones I have found. Below is a brief tutorial on how to use Mockrunner. (Keep in mind that I am still fairly new to using Mockrunner)<span id="more-285"></span></p>
<p>In the class I am testing I am explicitly calling the columns I am retrieving by name. So I need to add these column names to my mock ResultSet.</p>
<pre class="java" name="code" style="display: none;">
result.addColumn("Date");
result.addColumn("High");
result.addColumn("Low");
result.addColumn("Condition");
result.addColumn("ID");</pre>
<p>Obviously I also retrieve data from a result set so I must also insert data into the mock ResultSet. There are several ways to do this, but the easiest I found was using a list. You must add elements to the list in the same order as you added columns to the ResultSet.</p>
<pre class="java" name="code" style="display: none;">
List&lt;Object&gt; rowItems = new ArrayList&lt;Object&gt;();
rowItems.add(new Date(0));
rowItems.add(72);
rowItems.add(56);
rowItems.add("Cloudy");
rowItems.add(1);</pre>
<p>In my actual test case I can verify that I am actually gathering the contents of the result set correctly and that the correct SQL statement was run.</p>
<pre class="java" name="code" style="display: none;">
prepareRS();
ForecastDAO dao = new ForecastDaoImpl(getConnection());
List&lt;Forecast&gt; forecasts = dao.getAllForecasts();

assertTrue(!forecasts.isEmpty());
verifySQLStatementExecuted("SELECT * FROM forecast");
assertEquals(73, forecasts.get(1).getHigh());</pre>
<p>This is but scratching the surface of MockRunner's potential and using mocks at large. I hope this brief tutorial was helpful in getting you started using MockRunner. You can checkout the entire test class <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/22/trunk/%20forecastaccuracychecker/forecastchecker/test/com/tld/dao/TestForecastDaoImpl.java" target="_blank">here</a> and the class that I am testing <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/20/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">here</a>. If you want to get an entire working version of the project be sure to read the <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/20/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">technical guide</a>. Let me know if you have any questions or want to add your own comments.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x60, created 9/14/09 */
google_ad_slot = "1115297999";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Mock' rel='tag' target='_blank'>Mock</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a>, <a class='technorati-link' href='http://technorati.com/tag/Testing' rel='tag' target='_blank'>Testing</a>, <a class='technorati-link' href='http://technorati.com/tag/Unit+testing' rel='tag' target='_blank'>Unit testing</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/mocking-jdbc-connections-with-mockrunner/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ramblings: Should unit tests talk to a data source?</title>
		<link>http://www.turnleafdesign.com/ramblings-should-unit-tests-talk-to-a-data-source</link>
		<comments>http://www.turnleafdesign.com/ramblings-should-unit-tests-talk-to-a-data-source#comments</comments>
		<pubDate>Thu, 05 Nov 2009 04:48:40 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Ramblings]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Mock]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=280</guid>
		<description><![CDATA[Last week I published an article on test driven development. One person who read my article (briefly) suggested I did not know that unit tests shouldn't talk to their data source. I plan on covering how to mock JDBC connections later this week, however I wanted to do some research to see if what my [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Framblings-should-unit-tests-talk-to-a-data-source"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Framblings-should-unit-tests-talk-to-a-data-source" height="61" width="51" /></a></div><p>Last week I published an article on test driven development. One person who read my article (briefly) suggested I did not know that unit tests <a href="http://www.reddit.com/r/programming/comments/9yq8p/an_intro_into_test_driven_development_with_junit4/c0f29uc" target="_blank">shouldn't talk to their data source</a>. I plan on covering how to mock JDBC connections later this week, however I wanted to do some research to see if what my critic says is an industry standard or a philosophical choice.</p>
<p>Surprisingly there seems to be relatively little information on this subject, or I have been incapable of finding information. From what I have gathered though, the theory that data sources should be mocked is sound, but its may not always be practical to implement it. Below is two reasons why data source connections should be mocked and three reasons why they should not. <span id="more-280"></span></p>
<h3>Why you should mock connections</h3>
<p><strong>Speed –</strong> Talking to a data source is one the primary operations that slows an application's performance. Most data sources require some sort of network connection and retrieving data is often a processor intensive task. Obviously performing these tasks take time. Unit tests are most useful when they are run automatically and frequently to ensure changes being made are not breaking the application. Unit tests that are run automatically should be somewhat speedy, by mocking a data source connection, this can reduce considerably the amount of time it takes to run unit tests.</p>
<p><strong>Remove the reliance on the data source logic –</strong> Unit tests should be testing relatively small parts of code, individual methods and/or small collections of methods. By connecting to a data source you are depending upon the logic of not only how you are connecting, but how the data source operates. This goes beyond the scope of what a unit test should be testing.</p>
<h3>Why you shouldn't mock connections</h3>
<p><strong>It's time consuming –</strong> Writing mocks can be a quite laborious task. I often avoid writing mocks like the plague, because even relatively simple mocks can require a considerable amount of time to get running and running correctly. Even my very simple example of running a single query against a five column table took several hours to setup. Granted this was my first time creating a JDBC mock and future mocks would be easier and quicker to write, but it would still take longer than simply connecting to my database.</p>
<p><strong>It's ugly –</strong> It takes a lot of typing to get even relatively simple mocks working. A lot of the rules that apply to how real business code should be written need not be followed when writing unit tests, that said looking at the code of a unit test shouldn't make your eyes bleed. Unit tests that cannot be easily maintained often become ignored when they break and broken unit test have no value (if ignored).</p>
<p><strong>It's not real – </strong>Mocks don't really care what you put into or take out of them. Real data sources are often not so forgiving. If I misspelled a column or table name in a query, a mock would not pick up on this (you can verify the sql statements run, but again that could be misspelled), where as a real database would. By actually connecting to the real data source you can be more confident that the application will perform its intended tasks.</p>
<h3>Why you should use your head</h3>
<p>Even within the same project there will be instances where mocking a connection to a data source is the right choice and instances when you should actually connect to a real data source. In the early stages of a project using mocks can be more practical as the structure of the data source is more abstract and subject to change. Rewriting a mock is often quicker and easier than restructuring a data source. However as a project matures and the unit tests become more complex, connecting to the real data source may be more practical as it is not only (more) well defined, but writing the mocks begins to require more time. As with all practices, you need decide which one is best to follow (or not) based upon your requirements and restrictions. Though I think it is worth noting standards are standards for a reason. Feel free to weigh in with your own thoughts on the subject.</p>
<p>Additional reading:<br />
<a href="http://www.javaranch.com/journal/2003/12/UnitTestingDatabaseCode.html" target="_blank">http://www.javaranch.com/journal/2003/12/UnitTestingDatabaseCode.html</a><br />
<a href="http://www.buunguyen.net/blog/unit-testing-the-data-access-layer.html" target="_blank">http://www.buunguyen.net/blog/unit-testing-the-data-access-layer.html</a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x60, created 9/14/09 */
google_ad_slot = "1115297999";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Best+practices' rel='tag' target='_blank'>Best practices</a>, <a class='technorati-link' href='http://technorati.com/tag/Mock' rel='tag' target='_blank'>Mock</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a>, <a class='technorati-link' href='http://technorati.com/tag/Testing' rel='tag' target='_blank'>Testing</a>, <a class='technorati-link' href='http://technorati.com/tag/Unit+testing' rel='tag' target='_blank'>Unit testing</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/ramblings-should-unit-tests-talk-to-a-data-source/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A brief intro into unit testing with JUnit</title>
		<link>http://www.turnleafdesign.com/a-brief-intro-into-unit-testing-with-junit</link>
		<comments>http://www.turnleafdesign.com/a-brief-intro-into-unit-testing-with-junit#comments</comments>
		<pubDate>Wed, 30 Sep 2009 23:42:10 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Noob Corner]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=145</guid>
		<description><![CDATA[Learning how to use the built-in IDE debuggers and write unit tests is as fundamental to being a developer as knowing how to write a for loop. These two tools will save you countless hours of frustration and help you write better code. Entire books are written on just these subjects, however today I will [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fa-brief-intro-into-unit-testing-with-junit"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fa-brief-intro-into-unit-testing-with-junit" height="61" width="51" /></a></div><p>Learning how to use the built-in IDE debuggers and write unit tests is as fundamental to being a developer as knowing how to write a for loop. These two tools will save you countless hours of frustration and help you write better code. Entire books are written on just these subjects, however today I will just give a simple tutorial on writing unit tests.<span id="more-145"></span> In this example I will be testing a <a href="http://www.turnleafdesign.com/?p=52" target="_blank">JavaBean</a> that could be used in a simple inventory system. You can download the project <a href="http://turnleafdesign.com/code_examples/UnitTestExample.zip" target="_blank">here</a>. If you need help setting up the project you can follow the instructions <a href="http://www.turnleafdesign.com/?page_id=142" target="_blank">here</a>.</p>
<blockquote><p>package com.dining;</p>
<p>public class Item {<br />
public String name;<br />
public int id;</p>
<p>public Item(String name, String id) throws IllegalArgumentException{<br />
if((name != null &amp;&amp; !name.equalsIgnoreCase("")) &amp;&amp; (id != null &amp;&amp; !id.equalsIgnoreCase("") &amp;&amp; id.matches("\\d*"))){<br />
this.name = name;<br />
this.id = Integer.parseInt(id);<br />
} else {<br />
throw new IllegalArgumentException("Invalid argument(s)");<br />
}<br />
}</p>
<p>public String getName() {<br />
return name;<br />
}</p>
<p>public void setName(String name) {<br />
this.name = name;<br />
}</p>
<p>public int getId() {<br />
return id;<br />
}</p>
<p>public void setId(int id) {<br />
this.id = id;<br />
}<br />
}</p></blockquote>
<p>For my unit test I want to make sure my two argument constructor is working as expected. That is, it will require me to give a valid name, a String object with at least one character, and a valid id, a number. If either of these arguments are incorrect I will throw an IllegalArgumentException.</p>
<p>First we need to create a unit test class to run unit tests. To do this I will create a JUnit class, in Eclipse you can right click in your package explorer view and in the pop menu scroll down to the “JUnit” option, be sure to do this under the “com.unittest” package in the “test” folder. I will be using JUnit 3 for this example. The convention for naming for unit test classes is “Test” followed by the name of the class you will be testing, so in this case “TestItem.” The defaults should be fine so go ahead and click ok.</p>
<p>Each unit test case is its own method. Again the convention with unit tests is to start the name with “test” followed by the method under test. This is can be a looser practice as you might want to name the unit test based upon the type of test your are running. In this case I will name the unit test “testItemValidArguments” because I will be only passing valid arguments into the constructor. Inside the unit test you will make a call to the method you are testing and you will run an assertion to check to make sure the right value is being returned. There are numerous assertion types:</p>
<p>assetEquals(expected, actual) which compares what you are expecting to what is actually returned<br />
assertTrue(condition) expects the passed condition to return true<br />
assertFalse(condition) expects the passed condition to return false</p>
<p>There are a couple of other ways of running tests but these are the major ones. When these methods return an unexpected value; unequal values, false when true expected and vice versa, this causes the test to fail. If you are running your test in Eclipse the JUnit view will display red. Conversely if the test passes the JUnit view will display Green.</p>
<p>So lets write our first unit test:</p>
<blockquote><p>public void testItemValidArguments() {<br />
Item item = new Item("Wrench", "1");<br />
assertEquals(2, item.getId());<br />
}</p></blockquote>
<p>No, I did not make a typo, go ahead and run the test an see what happens. Your test should fail (if it doesn't you have a problem). The JUnit view should look like this:<br />
<img src="http://turnleafdesign.com/code_examples/UnitTestImages/Picture%202.png" alt="" /></p>
<p>JUnit will let you know when you failed a test. In this case it's telling us that it was expecting “2” to be returned, but actually got “1.” Go ahead and change the expected value back to “1” and run the test again and it should pass. Ok so when we pass valid arguments the constructor works correctly. Now let's make sure the constructor lets us know when the arguments passed in are not valid. Let's write another units test:</p>
<blockquote><p>public void testIteamInvalidArguments() {<br />
Item item = new Item("Wrench", "A");<br />
assertEquals(“A”, item.getId());<br />
}</p></blockquote>
<p>Try running the test. Your JUnit view should look like this:<br />
<img src="http://turnleafdesign.com/code_examples/UnitTestImages/Picture%203.png" alt="" /><br />
Well good news bad news. The constructor validates the second field correctly, it is requiring a number, however we don't want our unit tests failing. All unit tests should “pass” when they run correctly so a change needs to be made. To cut to the chase this is one possible way of fixing the unit test:</p>
<blockquote><p>public void testIteamInvalidArguments() {<br />
try {<br />
Item item = new Item("Wrench", "A");<br />
fail("You should have thrown an exception!");<br />
} catch (IllegalArgumentException e) {<br />
//Do nothing<br />
}<br />
}</p></blockquote>
<p>As long as a fail is not returned within a JUnit test case the test passes, so in the test case if the IllegalArgumentException is thrown then we won't do anything because we are expecting that, however if the exception is not thrown then we want the test to fail. So on the line below where I create an Item object I call fail() and pass in a message, so if the exception is not thrown the test will fail and I will know I have a problem (and a message will be displayed in the JUnit view).</p>
<p>I will end my tutorial here. This should be enough to get your feet wet in unit testing. There are several other tests that could be written, for example checking to make sure name validation works. I plan on covering this subject in more depth so check back later. This is my first real tutorial, so please let me know if I glossed over anything. If you have any other questions please let me know.</p>
<p style="text-align: center;"><script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x15, created 9/22/09 */
google_ad_slot = "6237316105";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Best+practices' rel='tag' target='_blank'>Best practices</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a>, <a class='technorati-link' href='http://technorati.com/tag/Testing' rel='tag' target='_blank'>Testing</a>, <a class='technorati-link' href='http://technorati.com/tag/Unit+testing' rel='tag' target='_blank'>Unit testing</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/a-brief-intro-into-unit-testing-with-junit/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
