I am trying to build a simple framework using JUnit for testing classes that use Hibernate to persist objects.
These tests will typically create a few objects, persist them to the database, read them back, update, etc. At the end of the test, I want all the objects I added out of the database.
My strategy for doing this is to place each object created in a list, and then iterate the list in reverse order in the tearDown() method and delete each object.
This strategy mostly works except for this: the unit tests may themselves want to test deletion, and then verify that the deleted object no longer exists in the database. However, if the test fails, I still want the tearDown() method to attempt to delete the object, even though it may no longer exist.
My first approach was to wrap each deletion in a try-catch block to catch the exceptions that may occur when the object has already been deleted, and just move on down the list.
But then I read "Chapter 20 - Best Practices" which tells me it's an awfully good idea not to treat exceptions as recoverable.
So my question is first whether what I am doing is really unsafe.
My second question is whether there's a method that will delete an object only if it exists, or whether I should just bite the bullet and try to get() the object (not load() which would throw) and only delete it if it's available.
|