Python unit test for a function that has try/except

13,584

Solution 1

If you really need this, one possible way is to mock out the log.error object. After invoking the func_A function, you can make an assertion that your mock wasn't called.

Note that you should not catch exceptions at all if you don't intend to actually handle them. For proper test coverage, you should provide 2 tests here - one which checks each branching of the try/except.

Solution 2

Another possible solution is to split implementation into two functions:

  1. Function foo() with logic without try statement. This way you can make sure that no exception is thrown in your implementation.
  2. safe_foo() which wraps foo() into try statement. Then you can mock foo() to simulate throwing an exception by it and make sure every exception is caught.

Drawback is that either foo() will be part of a public interface or you will write tests for a private function.

Share:
13,584
leopoodle
Author by

leopoodle

Updated on June 26, 2022

Comments

  • leopoodle
    leopoodle almost 2 years

    I have a function that has try/except as follows:

    def func_A():
      try:
           # do some stuff
      except Exception as e:
         log.error("there was an exception %s", str(e))
    

    I want to write a unit test for this func_A() More importantly, I want to ensure that

    • No exception was caught inside A

    I have try/except just for safety. Unless there is a bug, there should be no exception thrown inside A (although it will be caught with try/except) and that's what I want to validate with my unit test.

    What is the best way for unit test to catch the case where there was an exception thrown and caught?