Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I force exceptions to test them?

i have this method in my data access class and i have a unit test to make sure it does work properly, but my test doesn't test the exception so my question is should i create a new test to force the exception to be raised or should i just trust that the catch block will work just fine in case of an exception ? is it worth the effort ?

here is an example :

public void UpdateProject(Project project)
    {
        using (var transaction = _session.BeginTransaction())
        {
            try
            {
                _session.Update(project);
                _session.Flush();
                transaction.Commit();
            }
            catch (HibernateException)
            {
                transaction.Rollback();
                throw;
            }
        }
    }
like image 483
Hannoun Yassir Avatar asked Sep 26 '09 18:09

Hannoun Yassir


2 Answers

Ideally, you should try to test every line of code that you can... this would mean forcing an exception to occur to test the exception handler, and make sure this works properly.

In practice, there will always be some lines of code not covered - however, I would force exceptions via mocking in order to test any exception handler that you feel is critical, especially, or that will possibly happen in production.

like image 111
Reed Copsey Avatar answered Sep 22 '22 15:09

Reed Copsey


In Linux kernel, 80% of bugs in drivers are in error-handling code.

Exceptional handling is the source of many errors and you surely should test all the exception paths.

Of course you can't test every line of code. But the statistic says that programmers pay less attention to exception handling, so you must test them thoroughly.

like image 22
P Shved Avatar answered Sep 21 '22 15:09

P Shved