Posts Tagged ‘java’
Integration Testing Queries
When you’re developing with databases, you will likely come across the need to test queries that insert, update or delete data. This usually creates a problem because the database tables quickly fill up with test data.
In one of my earlier engagements, we were using Hibernate to map a complex graph of objects. Not only did we need to test whether the usual CRUD operations worked with one object in isolation, but with entire graphs of objects. For example, deleting a customer record should delete all records from customer_orders, customer_contacts etc.
We wrote our integration tests using JUnit. To avoid cluttering the database, we used a strategy where we explicitly started a transaction in our setUp() method and rolled it back in tearDown(). The code was (somewhat) like this:
protected void setUp() throws Exception {
session = HibernateSessionFactory.newSession();
transaction = session.beginTransaction();
}
protected void tearDown() throws Exception {
session.flush();//fire all sql updates..
transaction.rollback();
HibernateSessionFactory.endSession(session);
}
In a later engagement, we came across the same problem. However, this time we were using the spring framework. The spring framework provides a class named AbstractTransactionalDataSourceSpringContextTests (Yes, the name is a mouthful). As the name suggests, this is a abstract class you can extend your (JUnit) test case from. It comes with all the usual spring auto-wiring capabilities, in addition, it automatically rolls-back the transaction at the end of each test. Regardless of the approach, integration test are a big time saver. I usually advocate integration tests for all methods invoked from a Controller (e.g.Struts Action). Having tests such as these in place makes it possible to test and debug almost all bugs right from the IDE. And thanks to the auto-rollbacks – without making a mess of test data.
On Commons Lang
One of my favorite open source libraries is the Jakarta commons. I find myself using some methods and classes all the time. The top few, based on how often they appear in my code, are:
-
StringUtils (org.apache.commons.lang)StringUtils.isNotEmpty(str): Sure beats having to do the following:if(str!= null && str.length() >0) { ---- }This can be expressed simply as:
if(StringUtils.isNotEmpty(str)){ ---- }StringUtils.isEmpty(str),StringUtils.isBlank(str),StringUtils.isNotBlank (str)have similar semantics, with intuitive handling of “null” variables.
Check out the API docs for more time-savers. -
ToStringBuilder (org.apache.commons.lang.builder)Like most others, I find it invaluable to have a well defined toString method in every class I write. This is especially true of stateful classes(domain objects, DTOs etc).
It is painful to write code like:public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("Last Name=").append(lastName); buffer.append("First Name=").append(firstName); }The quick and easy:
return ToStringBuilder.reflectionToString(this);
If you want to customize which fields are included/excluded, it’s still simpler than using StringBuffer:
return new ToStringBuilder(this). append("firstName",this.firstName). append("lastName",this.lastName).toString();Note: There are many options available like changing the default output format, including the superclass etc. Check out the API for more details.
-
EqualsBuilder and HashCodeBuilder (org.apache.commons.lang.builder)Again, a really simple way to write good
equalsandhashCodemethods:public boolean equals(Object other) { return EqualsBuilder.reflectionEquals(this, other); } public int hashCode() { return HashCodeBuilder.reflectionHashCode(17,37,this); }See Also:
CompareToBuilder -
Validate (org.apache.commons.lang)A good practice is to always ensure that arguments to a method call are correct. For example,
public void doSomething(Long aLong, Collection aCollection){ if(aLong == null) { throw new IllegalArgumentException("aLong is null"); } if(aCollection == null || aCollection.isEmpty()) { throw new IllegalArgumentException( "aCollection is null or empty"); } --- }This can be expressed more concisely:
public void doSomething(Long aLong, Collection aCollection){ Validate.notNull(aLong, "aLong is null"); Validate.notEmpty(aCollection, "aCollection is null or empty"); ----- }
The above mentioned are but a few of the useful and elegant methods on the commons lang API. The web site is http://jakarta.apache.org/commons/lang/