2

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>) {
    //statments
    try {
        // database call
        database.insert(<Argument>);
    }
    catch {
        logger.error();
        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() {
    //setup
    database = ..//

    when(database)
    .calls(insert)
    .return(Exception);

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

    }
    Assert.fail();
}
1
  • 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
    Feb 6, 2018 at 8:14

1 Answer 1

2

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.

0

Your Answer

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

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