Posts

Showing posts from March, 2009

Simple transactional unit testing database

Last week I wrote a post about using Google Guice to perform transaction handling using interceptors . When it came time to write some database level unit tests, I wanted to have the same kind of simple transaction handling so that every unit test is rolled back on completion. Rolling back the changes each test makes is necessary for the tests to be repeatable and consistent . TestNG provides convenient way to do processing before and after each method is called using @BeforeMethod and @AfterMethod . All you need to do is annotate methods that you want automatically rolled back with @Transactional then check for it and act accordingly. The same could be done with JUnit using a RunListener . Below is my implementation. I use just one connection per unit test, it can easily be adapted across multiple connections. public abstract class BaseUtilTest { private static final Logger log = Logger.getLogger(BaseUtilTest.class); protected Connection con; @BeforeClass public void init()

Lightweight transaction handling in Tomcat

With Enterprise Java Beans (EJB) used with Container-Managed Transactions (CMT), transactions are transparently handled by the application server. When a method is marked with @TransactionAttribute(REQUIRED) then it starts a transaction (if one is not already started) and on competition of the method commits it (if it created the transaction). If an exception occurs, then the container rolls back the transaction. The beauty of it, is that it requires no extra code, just a single annotation. However, if running outside an application server, e.g. in a Tomcat only environment, then container managed transactions cannot be used. The common approach would be to use Spring. Spring provides the same functionality as EJB's but with a few drawbacks. It requires a large number of libraries to be included in your classpath plus a cumbersome to maintain configuration file just to set up some basic transaction handling. Spring does have its advantages but is overkill in a lot of cases. E