I have a function/method which throws some exception when database is being called. I was writing Junit tests and I was told to have good coverage. So, should I write Junit test which catches exception. I think it don't make any sense, since I have to mock the database to do so.

So whole scenario will be like this:

public <returntype> method(<arguments>) {
    try {
        // database call
    catch {
        return error;

It makes sense only when there is something good in catch statment. But if its only logging, then there is no point having a Junit test for this.

So should, I write these test?

public void test_catch_Exception() {
    database = ..//


        //some statements for execution of the method
    catch(Exception e) {

  • 1
    since I have to mock the database to do so this is what unit tests are all about. Isolating components under test from certain dependencies. For instance, DB.
    – Laiv
    Commented Feb 6, 2018 at 8:14

1 Answer 1


For your particular code excerpt, you don't need a catch(Exception e) followed by an Assert.fail. If an exception is not caught then the test will fail anyway. You should definitely assert that when the DB exception is thrown you end up getting the "error" from your method (i.e., return error bit).

The point of unit testing is to verify effects and side effects of a method. If your method logs an error and your production management team considers such a log to be of vital importance then it makes sense to also assert that a call to the logger.error (or whatever you used) was made with the right arguments (e.g., the exception that was thrown itself). You can achieve that through Mockito.verify. To verify the actual log file will probably be an overkill.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.