|
Testing the Transaction Handler
JUnit is the obvious choice when testing whether the transaction handling works as intended. Here's some code that will try to insert the same DVD twice. This results in an error and forces a rollback. The test determines whether the firstcorrectly insertedDVD has been rolled back and is no longer in the database:
public void testTransaction4() throws DAOException {
trans.begin();
String id = "ID3";
String title = "Troy";
manager.createDVD(id, title);
// Check for correct insert
DVD dvd = manager.getDVD(id);
assertNotNull("Test for ID3", dvd);
// Try a double insert
try {
manager.createDVD(id, title);
fail("Double create must throw an exception");
} catch (DAOException e) {
trans.rollback();
}
// Check that the inserted record has been rolled back
dvd = manager.getDVD(id);
assertNull("Test for ID3", dvd);
}
If the test is successful, the JUnit will show a "green bar."
Flexibility Through Interfaces
Now you know how to use a Transaction object to manage DAO transactions in a simple and back-end neutral way. There is a set of conventions that have to be followed: the business logic must call the begin/end/rollback methods on the Transaction object, but that's all. By using interfaces to define DAOs and the Transaction object, it's a simple thing to replace the back-end system. This is especially useful during testing, since this allows you to use a mock-up of the back-end.
Happy coding!
Related Resources
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|