In an ideal world, a unit test should only test a small piece of code, should be repeatable, and be independent of external dependencies such as application servers and databases. However, because of legacy code constraints and budgeting concerns (among other reasons), it's not always possible to write ideal tests. Code that depends on databases can be especially difficult to test because of the time it takes to mock and test. On the other hand, if real database code is used in the test, it is often difficult to make test runs repeatable due to the nature of real-world data.
Writing coarse-grained tests is an option. One benefit of coarse-grained tests is that they can test the integration points of dependant components. For instance, Java-based enterprise applications typically use Enterprise Java Bean (EJB) technology. Most EJB components depend either directly or indirectly on the database to complete processing. Such components can be difficult to test because it takes time to write, build, deploy, and see verify that the code works correctly. In this article I show how you can write coarse-grained repeatable unit tests for such components using OpenEJB and DBUnit. The complete source code and related files are available The complete source code and related files are available here.
To examine coarse-grained testing, I use the example of a spaceship ticket booking application. Blue Star Galactic is a small spaceship company that transports people from one place to another place within our galaxy. Being a transportation company, it requires ticket booking software. The requirements for the software are straightforward: Since the spaceships are small, they can only transport five passengers at a time. Consequently, the booking engine should limit five ticket bookings for the same destination. And since only one person can travel with the same name from one place to another, the application should not allow the same passenger to book more than one ticket in the same name for the same source and destination.
All the tickets need to get stored somewhere. I chose MySQL database since it is open source and straightforward to setup. You can use any database you want with few minor changes in JDBC properties. After installing MySQL, I created a database called "spaceship". Then I created a table called "Ticket" to store the ticket bookings with columns as in Figure 1.
That's all the app requires from the database setup side. Scripts to create the database and table are also included in the project under db-scripts folder (available here.). While this app is simple, it scales to larger, more complex projects. Finally, I use the Eclipse IDE but without installing any additional plug-ins. Figure 2 depicts the key components of the application.