JUnit tests, Hibernate, and Netbeans 4.1
Here is a quick little tip if you are trying to write tests in JUnit for Hibernate. When you are going to catch exceptions, do not put a generic catch(Exception e) { } block at the end of your code as this will mask any other exceptions that might be thrown with a standard Netbeans/JUnit exception. What this means is that instead of getting anything useful out of the stack trace, you will only get a very generic, non-useful message relating to JUnit and not what you were trying to do. Therefore, catch any specific exceptions like HibernateException and let the rest just fall through and be displayed on screen.
I found this out trying to test the insertion of some objects I had created. The insertions weren’t working and I wasn’t getting any helpful errors. As soon as I added a specific catch block for HibernateException I got all the messages I needed.
This is a good tip - but not one that is exclusive to JUnit, Hibernate or NetBeans.
The practice should be carried out in all Java exception handling.
Always catch the exception class that you expect the code to throw - ALMOST NEVER Exception - as this will…
a) State your intent more clearly to others (and yourself, during futre re-visits to the code)
b) Leverage the power of the compiler to inform you of new exception types that my be thrown by any code you add to the try block in future.
I’m sure that there are many other articles on the subject, so I won’t elaborate further - unless the demand is sufficient.
This is very true. I guess for me, the affects of this became very obvious when trying to test my Hibernate mapping files.