As @hoefling pointed out, your function doesn't raise anything, so your test result is correct. Probably you don't need to check if the exception is raised, but how your method is behaving in this case.
To check for the print
call, you can just mock it and check the calls:
from unittest import mock
def raise_and_catch_exception(do_raise):
# example function that raises and catches an exception
try:
if do_raise:
raise ValueError()
except ValueError:
print('Raised exception')
@mock.patch('my_tested_module.print')
def test_print(mocked_print):
raise_and_catch_exception(False)
mocked_print.assert_not_called()
raise_and_catch_exception(True)
mocked_print.assert_called_once_with('Raised exception')
In case you want to check if the exception is raised anyway, you can mock the exception itself. Note that cannot just replace the exception by a mock, because Python would complain that your exception is not raised from BaseException
while trying to execute the exception handler. Here is some crude example how you could do this:
...
class MyException(ValueError):
call_nr = 0 # note that this counts the instancion of the exception, not raising it
def __init__(self, *args):
self.__class__.call_nr += 1
super().__init__(*args)
def test_raise():
with mock.patch('builtins.ValueError', MyException):
raise_and_catch_exception(False)
assert MyException.call_nr == 0
raise_and_catch_exception(True)
assert MyException.call_nr == 1