<?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>Java Joe &#187; spring</title>
	<atom:link href="http://josephkampf.com/javajoe/tag/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://josephkampf.com/javajoe</link>
	<description>Joseph Kampf&#039;s musings on Java, Technology and Business</description>
	<lastBuildDate>Wed, 02 May 2012 13:29:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Mock Data Testing with Spring and HSQLDB part 2</title>
		<link>http://josephkampf.com/javajoe/2009/12/22/mock-data-testing-with-spring-and-hsqldb-part-2/</link>
		<comments>http://josephkampf.com/javajoe/2009/12/22/mock-data-testing-with-spring-and-hsqldb-part-2/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 20:39:30 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[Java Programing]]></category>
		<category><![CDATA[hsqldb]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/?p=51</guid>
		<description><![CDATA[This is my 2nd post about Mock Data Testing using Spring and HSQLDB.  If you missed my first post you can find it here. I know that this concept is not really bleeding edge. The whole purpose of these two posts are to share an approach that I have used in the past to help [...]]]></description>
			<content:encoded><![CDATA[<p>This is my 2nd post about Mock Data Testing using Spring and HSQLDB.  If you missed my first post you can find it <a href="http://josephkampf.com/javajoe/2009/11/24/mock-data-testing-with-spring-and-hsqldb-part-1/">here.</a></p>
<p>I know that this concept is not really bleeding edge.  The whole purpose of these two posts are to share an approach that I have used in the past to help me with my Test Driven Continuous development.  I have not tried it with Hibernate or any other ORM.  I have only used it with Spring JDBC Template and straight JDBC programing.</p>
<p>Architecture<br />
First let me explain the requirements for your architecture to be able to support this type of mock tests.  A good architecture allows components to be unit tested.  If you need an entire environment stack to be able to unit test your code then your architecture is just a big mess.  Business logic layer needs to be separate from your data access.  Your interface layer needs to be seperate from your business logic layer.   This is true if you are doing a MVC web application or even a back end SOA implementation.  I&#8217;m not just talking about encapsulating these different layers in different classes, but also have these layers be loosely coupled.</p>
<ol>
<li>Your Database queries should be externalized.  Do not hard code database queries or stored procedure calls.  I know that Hibernate allows you to annotate your code.  But can be a barrier to having your database access be portable.    However, you can get around this.  Configuration of your Database access should be loaded at run time.  Spring Beans do a nice job of handling this.  The Bean XML file gives you a great way to capture configuration information and load it at run time.  The Application Configuration allows you to load these files external to your actual business logic.</li>
<li>Your modules should be able to be run independent of any other infrastructure.  Make your modules Pojos.  Even if you plan to expose them as EJBs, MDBs or Web Services.  You can code your business logic as a Pojo.  This will allow simple clean unit tests that can run right out of the command line with no other application running.</li>
</ol>
<p>Unit Test Implementation<br />
So lets start with the Java code.. Below is an example of a simple Pojo that does some sort of business logic. (I left out the get/setters and import statements.)</p>
<pre>public class BusinessPojo {

    private String sql;

    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    public String doSomething(String id) {
	SqlRowSet rowset = getJdbcTemplate().queryForRowSet(getSql(), new Object[] { id });

	return rowset.getString("Field1");
    }
}</pre>
<p>This example defines 2 bean properties.  The first is the SQL string that is executed, the second is the JDBC Datasource that the SQL is being executed against.  The Pojo also uses the JDBC Template from the Spring framework.  This is only to hide a lot of the messy JDBC code.</p>
<p>This is a very simple example.  But it can easily be extended to take any number of input parameters and any number of returned values.<br />
Also, this approach can be used with any framework that you can pass a JDBC Datasource and a SQL statement to.</p>
<p>Now let&#8217;s look at our test class:</p>
<pre>package com.josephkampf.example;

import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import org.apache.commons.io.IOUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 * Unit test for the BusinessPojo.
 *

 *
 * @author Joseph Kampf (me@josephkampf.com)
 */
public class BusinessPojoTest {

    private ApplicationContext ctx;

    @BeforeClass
    public void setup() throws Exception {
	setUpHSQLDB("BusinessPojoTest", "/TestBusinessPojoSchemaSetup.sql");
	setUpHSQLDB("BusinessPojoTest", "/TestBusinessPojoDataSetup.sql");
	this.ctx = new ClassPathXmlApplicationContext(
		"spring-TestBusinessPojo.xml");
    }

    /**
     * Sets up the in-memory HSQLDB using the database name and initial SQL
     * script to populate the database.
     */
    public void setUpHSQLDB(String databaseName, String initSqlScript)
	    throws Exception {

	Class.forName("org.hsqldb.jdbcDriver");

	final URL url = this.getClass().getResource(initSqlScript);
	final String sql = IOUtils.toString((InputStream) url.getContent());

	final Connection connection = DriverManager.getConnection(
		"jdbc:hsqldb:mem:" + databaseName, "sa", "");
	final Statement s = connection.createStatement();
	s.execute(sql);

	s.close();
	connection.close();

    }

    @Test
    public void testProcess() throws Exception {
	BusinessPojo pojo = (BusinessPojo) this.ctx.getBean("pojo");
	Assert.assertEquals(pojo.doSomething("ID1"), "Expected");
    }
}</pre>
<p>I use TestNG.  I Like TestNG because it is annotation driven. Let&#8217;s take a look at what is going on in this test outside of actually testing the Pojo.</p>
<p>Take a look at the setUpHSQLDB method.  This method takes a name and looks up via a JDBC URL an in memory HSQLDB instance.  If the instance does not exist, it is created.  So we can always reference this instance again by using the same JDBC URL.  We will see this later when we create our BusinessPojo Test Spring context file.  The method also executes some SQL scripts in the in Memory Database.  The first sets up the table structures.  The second addes the data.  I&#8217;m not going to go into the details of what is in these scripts.  I&#8217;ll leave some examples as an attachment to this posting.  I refer you to the HSQLDB online documentation for details.  But what is happening here is the database is being set up in a known state in the same JVM that our unit test is running in.  No extra processes are required.</p>
<p>Note that we could take the setUpHSQLDB method and create a Test Fixture.  This is actually how I have implemented it in my code.  However I leave it all in one class for convenience.  Another option would be to add the setUpHSQLDB method in your base class. (Not the way I would go.)</p>
<p>Now lets connect our Pojo to the HSQLDB instance we have created in our Unit Test.  Below is the Spring Configuration that is loaded by the Unit Test.</p>
<pre>spring config:
&lt;beans&gt;
 &lt;bean id="pojo" class="com.josephkampf.example.BusinessPojo"&gt;
   &lt;property name="dataSource"&gt;
     &lt;ref bean="dbcpDataSource" /&gt;
   &lt;/property&gt;
   &lt;property name="sql"&gt;
     &lt;value&gt;SELECT f1 as Field1 from sample_table where id = ?&lt;/value&gt;
   &lt;/property&gt;
 &lt;/bean&gt;

 &lt;bean id="dbcpDataSource" destroy-method="close"&gt;
   &lt;property name="driverClassName" value="org.hsqldb.jdbcDriver" /&gt;
   &lt;property name="url" value="jdbc:hsqldb:mem:BusinessPojoTest" /&gt;
   &lt;property name="username" value="sa" /&gt;
   &lt;property name="password" value="" /&gt;
 &lt;/bean&gt;
&lt;/beans&gt;</pre>
<p>Notice the url of the DataSource.  It has the form of jdbc:hsqldb:mem:<strong>BusinessPojoTest</strong>.  Notice that this is the same JDBC URL we used in our Unit Test to load up the database.  So when the Spring template obtains a connection, it will be obtaining a connection to the in memory HSQLDB instance.</p>
<p>Non-Unit Test Implementation<br />
Now when you actually go to a non-unit test environment, you will need a diffrent Spring Application Context file.  Below is an example of an Application Context that defines this Pojo to connect to an Oracle Database.  This is an example of what you might use in an environment that is beyond Unit test.(Integration, QA, Stage, Production, etc.)</p>
<pre>&lt;beans&gt;
  &lt;bean id="processor" class="com.josephkampf.example.BusinessPojo"&gt;
    &lt;property name="dataSource"&gt;
      &lt;ref bean="oracleDataSource" /&gt;
    &lt;/property&gt;
    &lt;property name="sql"&gt;
      &lt;value&gt;SELECT oracleField1 as Field1 from oracle_sample_table where id = ?&lt;/value&gt;
    &lt;/property&gt;
  &lt;/bean&gt;

  &lt;bean id="oracleDataSource"&gt;
    &lt;!-- Insert Oracle datasource configuration here. --&gt;
  &lt;/bean&gt;
&lt;/beans&gt;</pre>
<p>Notice that the SQL has changed to conform to the Oracle database.  All that matters is that both SQL values have the same structure for the <em>Select</em> clause have the same fields by name and the <em>Where</em> clause have the same number and order of the bind variables.</p>
<p>Mock Data Testing is an important step to delivering on a Test driven and continuous development effort.  You really should not need a running external database to be able to run your Unit Tests.  Your Unit Tests should be using a known set of data so that you can do meaningful Assertions in your Unit Test code.  You also need to be able to spend less time coding that Mock Data.  Using SQL to define this test data is a more intuitive and faster mechanism than other solutions.  Spring allows you to separate your concerns so that you can create testable units.</p>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2009/12/22/mock-data-testing-with-spring-and-hsqldb-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mock Data Testing with Spring and HSQLDB part 1</title>
		<link>http://josephkampf.com/javajoe/2009/11/24/mock-data-testing-with-spring-and-hsqldb-part-1/</link>
		<comments>http://josephkampf.com/javajoe/2009/11/24/mock-data-testing-with-spring-and-hsqldb-part-1/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 21:14:33 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[Java Programing]]></category>
		<category><![CDATA[hsqldb]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/?p=50</guid>
		<description><![CDATA[I wanted to share some interesting things that myself and my colleague Emil &#8220;Bud&#8221; Lefkof have done recently in the realm of Mock Testing using Spring and HSQLDB. I expect this to be the first of threetwo posts on this topic. First I&#8217;ll explain the problem that this approach solves. In the second post I&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to share some interesting things that myself and my colleague Emil &#8220;Bud&#8221; Lefkof have done recently in the realm of Mock Testing using Spring and HSQLDB.</p>
<p>I expect this to be the first of <del datetime="2009-12-22T20:37:53+00:00">three</del>two posts on this topic.  First I&#8217;ll explain the problem that this approach solves.  In the second post I&#8217;ll explain the approach.  In the last post I&#8217;ll discuss some additional concerns such as having to deal with Stored Procedures.</p>
<p>For an explanation of Mock Object Testing see <a title="Mock Object at Wikipedia" href="http://en.wikipedia.org/wiki/Mock_object" target="_blank">Wikipedia</a> who actually does a nice job of explaining what it is all about.  </p>
<p>The reason that Mock Testing is important is that Unit tests should be repeatable and automated.  Developers should be able to check out code and unit tests from a source control system and be able to run a script or command that builds and tests.  Unit tests shouldn&#8217;t need to rely on databases, or other external dependencies.  Plus the state of a database can become unknown.  When doing test driven development you need to be able to run a test over and over again.  You can&#8217;t worry about the data already being in the database.</p>
<p>I was first introduced to the concept of Mock Testing by my old friend and colleague Howard Spector during my time at FirstUSA/Bank One Card Services.  It was my first experience with Test Driven Development.  Back in those days we had our own Data Services Framework.  This was a framework that provided an interface that was an abstraction over Relational Database.</p>
<p>Because this framework was an interface we could use test implementations that would return mock data objects.  However it always felt clumsy.  Creating the test data was a manual time consuming task.  There were 2 ways to create the Mock Data objects.  </p>
<p>The first way is to hand code a factory that would set the values of the properties of data objects.</p>
<pre>
public List getDataPojos(String arg){
  List returnList = new LinkedList();

  DataPojo dataPojo1 = new DataPojo();
  dataPojo1.setString1("String 11");
  dataPojo1.setString2("String 12");
  returnList.add(dataPojo1);

  DataPojo dataPojo2 = new DataPojo();
  dataPojo2.setString1("String 21");
  dataPojo2.setString2("String 22");
  returnList.add(dataPojo2);

  return returnList;
}
</pre>
<p>Another option that has a little bit more flexibility is to parse a properties file or XML file.  </p>
<p>With either approach there needs to be some sort of translation from the source to the Mock Data object that is essentially throw away code.  This will cause the developer to spend more time writing code to create Mock Data objects than writing the actual tests or even the actual code.  </p>
<p>In my next <a href="http://josephkampf.com/javajoe/2009/12/22/mock-data-test…-hsqldb-part-2/">post</a> I&#8217;ll detail how we can solve the issue of spending too much time creating Mock Data objects.</p>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2009/11/24/mock-data-testing-with-spring-and-hsqldb-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

